Here you can copy some Java Programming collections for beginner. This code is simple and easy to understand.
1. How to convert array to collection:
import java.util.*;
import java.io.*;
public class ArrayToCollection{
public static void main(String args[])
throws IOException{
BufferedReader in = new BufferedReader
(new InputStreamReader(System.in));
System.out.println("How many elements
you want to add to the array: ");
int n = Integer.parseInt(in.readLine());
String[] name = new String[n];
for(int i = 0; i < n; i++){
name[i] = in.readLine();
}
List list = Arrays.asList(name);
System.out.println();
for(String li: list){
String str = li;
System.out.print(str + " ");
}
}
}
Result:
How many elements you want to add to the array:
red white green
red white green
2. How to overloads methods?
class MyClass {
int height;
MyClass() {
System.out.println("bricks");
height = 0;
}
MyClass(int i) {
System.out.println("Building new House that is "
+ i + " feet tall");
height = i;
}
void info() {
System.out.println("House is " + height
+ " feet tall");
}
void info(String s) {
System.out.println(s + ": House is "
+ height + " feet tall");
}
}
public class MainClass {
public static void main(String[] args) {
MyClass t = new MyClass(0);
t.info();
t.info("overloaded method");
//Overloaded constructor:
new MyClass();
}
}
Result:
Building new House that is 0 feet tall.
House is 0 feet tall.
Overloaded method: House is 0 feet tall.
bricks
No comments:
Post a Comment