Friday, April 13, 2018

Some random notes on Java basics

Arrays and Lists

How to initialize an Array?

// 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};

How to copy an Array?

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);

How to initialize a List?

// 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);

How to copy a List?

List newList = new ArrayList(otherList);

How to convert an Array of primitives to a List?

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());

How to convert an Array of non-primitives to a List?

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