Arrays and Lists
// Initialize by specifying the length (values default to 0)
int[] a = new int[5];
a[0] = 1;
// Initialize by specifying the values
int[] b = new int[]{1, 0, 0, 0, 0};
int[] source = new int[]{1,2,3,4,5};
// Copy the whole array using Object.clone()
int[] a = source.clone();
// Copy from the beginning to a given index
int[] b = Arrays.copyOf(source, source.length);
// Copy from a given index to a given index
int[] c = Arrays.copyOfRange(source, 0, source.length);
// Copy from source from index to destination from index the given amount of items (void method)
int[] d = new int[source.length];
System.arraycopy(source, 0, d, 0, source.length);
// Initialize with the new keyword
List a = new ArrayList<>();
a.add(1); a.add(0); a.add(0); a.add(0); a.add(0);
// Initialize with Arrays.asList
List b = Arrays.asList(1, 0, 0, 0, 0);
List newList = new ArrayList(otherList);
int[] source = new int[]{1, 0, 0, 0, 0};
// convert with for-each loop
List a = new ArrayList<>();
for (int n : source) {
a.add(n);
}
// convert with streams
List b = Arrays.stream(source).boxed().collect(Collectors.toList());
String[] strings = new String[]{"a", "b", "c"};
List<String> l = Arrays.asList(strings);
Scanner
If you want to read with Scanner from console input (System.in) in multiple methods within a single class you should only have one instance of that scanner.
Because "
after calling Scanner.close() on a Scanner which is associated with System.in, the System.in stream is closed and not available anymore."
Scanner s = new Scanner(System.in);
function1(s);
function2(s);
function3(s);
s.close();
No comments:
Post a Comment