Chapter 5 Core Java APIs Notes Flashcards

1
Q

+ operator rules:

A
  1. If both operands are numeric, + means numeric addition.
  2. If either operand is a String, + means concatenation.
  3. The expression is evaluated left to right.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

IMPORTANT STRING METHODS

A
  1. int length()
    returns the number of characters in the String.
  2. char charAt(int index)
    query the string to find out what character is at a specific index.
  3. int indexOf(int ch)
    int indexOf(int ch, int fromIndex)
    int indexOf(String str)
    int indexOf(String str, int fromIndex)
    looks at the characters in the string and finds the first index that matches the desired value.
    Remember that a char can be passed to an int parameter type.
    indexOf() returns –1 when no match is found.
  4. String substring(int beginIndex)
    String substring(int beginIndex, int endIndex)
    It returns parts of the string.
  5. String toLowerCase()
    String toUpperCase()
  6. boolean equals(Object obj)
    boolean equalsIgnoreCase(String str)
    equals() takes an Object rather than a String. This is because the method is the same for all objects. If you pass in something that isn’t a String, it will just return false.
  7. boolean startsWith(String prefix)
    boolean endsWith(String suffix)
  8. String replace(char oldChar, char newChar)
    String replace(CharSequence target, CharSequence replacement)
    does a simple search and replace on the string.
  9. boolean contains(CharSequence charSeq)
    looks for matches in the String.
  10. String strip()
    String stripLeading()
    String stripTrailing()
    String trim()
    The strip() method is new in Java 11. It does everything that
    trim() does, but it supports Unicode.
  11. String intern()
    returns the value from the string pool if it is there. Otherwise, it adds the value to the string pool.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
String string = "animals";
System.out.println(string.charAt(0)); // a
System.out.println(string.charAt(6)); // s
System.out.println(string.charAt(7)); // throws exception
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
String string = "animals";
System.out.println(string.indexOf('a')); // 0
System.out.println(string.indexOf("al")); // 4
System.out.println(string.indexOf('a', 4)); // 4
System.out.println(string.indexOf("al", 5)); // -1
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
String string = "animals";
System.out.println(string.substring(3)); // mals
System.out.println(string.substring(string.indexOf('m'))); // mals
System.out.println(string.substring(3, 4)); // m
System.out.println(string.substring(3, 7)); // mals

System.out.println(string.substring(3, 3)); // empty string
System.out.println(string.substring(3, 2)); // throws exception
System.out.println(string.substring(3, 8)); // throws exception
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
System.out.println("abc".strip()); // abc
System.out.println("\t a b c\n".strip()); // a b c
String text = " abc\t ";
System.out.println(text.trim().length()); // 3
System.out.println(text.strip().length()); // 3
System.out.println(text.stripLeading().length()); // 4
System.out.println(text.stripTrailing().length());// 4
A

First, remember that \t is a single character. The backslash escapes the t to represent a tab.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

> [!Note:]
You don’t need to know about Unicode for the exam. But if you want to test the difference, one of Unicode whitespace characters is as follows:
Unicode whitespace characters is as follows:

char ch = '\u2000';

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
10: String alpha = "";
11: for(char current = 'a'; current <= 'z'; current++)
12:     alpha += current;
13: System.out.println(alpha);

15: StringBuilder alpha = new StringBuilder();
16: for(char current = 'a'; current <= 'z'; current++)
17:     alpha.append(current);
18: System.out.println(alpha);
A
abcdefghijklmnopqrstuvwxyz
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
4: StringBuilder sb = new StringBuilder("start");
5: sb.append("+middle"); // sb = "start+middle"
6: StringBuilder same = sb.append("+end"); // "start+middle+end"
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
4: StringBuilder a = new StringBuilder("abc");
5: StringBuilder b = a.append("de");
6: b = b.append("f").append("g");
7: System.out.println("a=" + a);
8: System.out.println("b=" + b);
A

printed:

a=abcdefg
b=abcdefg
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

There are three ways to construct a StringBuilder:

A
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder("animal");
StringBuilder sb3 = new StringBuilder(10);
  • The first says to create a StringBuilder containing an empty sequence of characters and assign sb1 to point to it.
  • The second says to create a StringBuilder containing a specific value and assign sb2 to point to it.
  • For the first two, it tells Java to manage the implementation details.
  • The final example tells Java that we have some idea of how big the eventual value will be and would like the StringBuilder to reserve a certain capacity, or number of slots, for characters.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

IMPORTANT STRINGBUILDER METHODS

A
  1. charAt(), work exactly the same as in the String class.
  2. indexOf(), work exactly the same as in the String class.
  3. length(), work exactly the same as in the String class.
  4. substring(), work exactly the same as in the String class.
  5. StringBuilder append(String str)
    It adds the parameter to the StringBuilder and returns a reference to the current StringBuilder.
  6. StringBuilder insert(int offset, String str)
    adds characters to the StringBuilder at the requested index and returns a reference to the current StringBuilder.
  7. StringBuilder delete(int startIndex, int endIndex)
    StringBuilder deleteCharAt(int index)
  8. StringBuilder replace(int startIndex, int endIndex, String newString)
  9. StringBuilder reverse()
  10. String toString()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
3: StringBuilder sb = new StringBuilder("animals");
4: sb.insert(7, "-"); // sb = animals-
5: sb.insert(0, "-"); // sb = -animals-
6: sb.insert(4, "-"); // sb = -ani-mals-
7: System.out.println(sb);

jshell> StringBuilder sb = new StringBuilder("animals");
jshell> sb.insert(8, "-");
|  Exception java.lang.StringIndexOutOfBoundsException: offset 8, length 7
|        at String.checkOffset (String.java:4576)
|        at AbstractStringBuilder.insert (AbstractStringBuilder.java:1170)
|        at StringBuilder.insert (StringBuilder.java:336)
|        at (#11:1)
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
StringBuilder sb = new StringBuilder("abcdef");
sb.delete(1, 3); // sb = adef
sb.deleteCharAt(5); // throws an exception

StringBuilder sb = new StringBuilder("abcdef");
sb.delete(1, 100); // sb = a
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q
StringBuilder builder = new StringBuilder("pigeon dirty");
builder.replace(3, 6, "sty");
System.out.println(builder); // pigsty dirty
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
StringBuilder builder = new StringBuilder("pigeon dirty");
builder.replace(3, 100, "");
System.out.println(builder);
A

prints:
pig

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

StringBuilder did not implement equals().
You can call toString() on StringBuilder to get a String to check for equality instead.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

THE STRING POOL

A

The string pool, also known as the intern pool, is a location in the Java virtual machine (JVM) that collects all these strings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q
String x = "Hello World";
String y = "Hello World";
System.out.println(x == y); // true
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q
String x = "Hello World";
String z = " Hello World".trim();
System.out.println(x == z); // false
A

Since it isn’t the same at compile-time, a new String object is created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q
String singleString = "hello world";
String concat = "hello ";
concat += "world";
System.out.println(singleString == concat);
A

This prints false. Concatenation is just like calling a method and results in a new String.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q
String x = "Hello World";
String y = new String("Hello World"); //create a new String 
System.out.println(x == y); // false
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q
String name = "Hello World";
String name2 = new String("Hello World").intern();
System.out.println(name == name2); // true
A
  • First we tell Java to use the string pool normally for name.
  • Then for name2, we tell Java to create a new object using the constructor but to intern it and use the string pool anyway.
  • Since both variables point to the same reference in the string pool, we can use the == operator.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q
15: String first = "rat" + 1;
16: String second = "r" + "a" + "t" + "1";
17: String third = "r" + "a" + "t" + new String("1");
18: System.out.println(first == second); // true
19: System.out.println(first == second.intern()); // true
20: System.out.println(first == third); // false
21: System.out.println(first == third.intern()); // true
A
  • On line 15, we have a compile-time constant that automatically gets placed in the string pool as “rat1”.
  • On line 16, we have a more complicated expression that is also a compile-time constant.
  • Therefore, first and second share the same string pool reference. This makes line 18 and 19 print true.
  • On line 17, we have a String constructor. This means we no longer have a compile-time constant, and third does not point to a reference in the string pool.
  • Therefore, line 20 prints false.
  • On line 21, the intern() call looks in the string pool. Java notices that first points to the same String and prints true.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

> [!Note:]
Remember to never use intern() or == to compare String objects in your code. The only time you should have to deal with these is on the exam.

A
26
Q

The basic structure of an array

A
int[] numbers = new int[3];
  1. Type of array
  2. Array symbol (required)
  3. Size of array
int[] numbers2 = new int[] {42, 55, 99};
int[] numbers2 = {42, 55, 99}; // anonymous array

int[] ids, types; // create 2 int array
int ids[], types; // ids is a int array, types is a int

// following do the exact same thing
int[] numAnimals;
int [] numAnimals2;
int []numAnimals3;
int numAnimals4[];
int numAnimals5 [];
27
Q

> [!Note:]
Since Java 5, Java has provided a method that prints an array nicely:
Arrays.toString(bugs) would print [cricket, beetle, ladybug].

A
28
Q
3: String[] strings = { "stringValue" };
4: Object[] objects = strings;
5: String[] againStrings = (String[]) objects;
6: againStrings[0] = new StringBuilder(); // DOES NOT COMPILE
7: objects[0] = new StringBuilder(); // careful!
A
  • Line 3 creates an array of type String.
  • Line 4 doesn’t require a cast because Object is a broader type than String.
  • On line 5, a cast is needed because we are moving to a more specific type.
  • Line 6 doesn’t compile because a String[] only allows String objects and StringBuilder is not a String.
  • Line 7 is where this gets interesting. From the point of view of the compiler, this is just fine. A StringBuilder object can clearly go in an Object[]. The problem is that we don’t actually have an Object[]. We have a String[] referred to from an Object[] variable. At runtime, the code throws an ArrayStoreException. You don’t need to memorize the name of this exception, but you do need to know that the code will throw an exception.
29
Q

ARRAY SORTING

A

of the following two statements in your class:

import java.util.*; // import whole package including Arrays
import java.util.Arrays; // import just Arrays
int[] numbers = { 6, 9, 1 };
Arrays.sort(numbers);
for (int i = 0; i < numbers.length; i++)
    System.out.print(numbers[i] + " ");

print:
1 6 9

String[] strings = { "10", "9", "100" };
Arrays.sort(strings);
for (String string : strings)
System.out.print(string + " ");

This code outputs:
10 100 9

30
Q

ARRAY SEARCHING

A

Java also provides a convenient way to search—but only if the array is already sorted.
Binary search rules:
1. Target element found in sorted array, return Index of match
2. Target element not found in sorted array, return Negative value showing one smaller than the negative of the index, where a match needs to be inserted to preserve sorted order
3. Unsorted array, will return A surprise—this result isn’t predictable

example:

31
Q

Arrays.binarySearch() examples:

3: int[] numbers = {2,4,6,8};
4: System.out.println(Arrays.binarySearch(numbers, 2)); // 0
5: System.out.println(Arrays.binarySearch(numbers, 4)); // 1
6: System.out.println(Arrays.binarySearch(numbers, 1)); // -1
7: System.out.println(Arrays.binarySearch(numbers, 3)); // -2
8: System.out.println(Arrays.binarySearch(numbers, 9)); // -5
A
  • line 3 is a sorted array.
  • Line 4 searches for the index of 2. The answer is index 0.
  • Line 5 searches for the index of 4, which is 1.
  • Line 6 searches for the index of 1. Although 1 isn’t in the list, the search can determine that it should be inserted at element 0 to preserve the sorted order. Since 0 already means something for array indexes, Java needs to subtract 1 to give us the answer of –1.
  • Line 7 is similar. Although 3 isn’t in the list, it would need to be inserted at element 1 to preserve the sorted order. We negate and subtract 1 for consistency, getting –1 –1, also known as –2.
  • Finally, line 8 wants to tell us that 9 should be inserted at index 4. We again negate and subtract 1, getting –4 –1, also known as –5.
32
Q
5: int[] numbers = new int[] {3,2,1};
6: System.out.println(Arrays.binarySearch(numbers, 2));
7: System.out.println(Arrays.binarySearch(numbers, 3));
A

The exam creators will not expect you to know what incorrect values come out. As soon as you see the array isn’t sorted, look for an answer choice about unpredictable output.

33
Q

ARRAY COMPARING

A
compare()
mismatch()
34
Q

compare()

A

compare() return:
1. A negative number means the first array is smaller than the second.
1. A zero means the arrays are equal.
1. A positive number means the first array is larger than the second.

how to compare arrays of different lengths:
1. If both arrays are the same length and have the same values in each spot in the same order, return zero.
1. If all the elements are the same but the second array has extra elements at the end, return a negative number.
1. If all the elements are the same but the first array has extra elements at the end, return a positive number.
1. If the first element that differs is smaller in the first array, return a negative number.
1. If the first element that differs is larger in the first array, return a positive number.

rules that apply here and to compareTo()
1. null is smaller than any other value.
1. For numbers, normal numeric order applies.
1. For strings, one is smaller if it is a prefix of another.
1. For strings/characters, numbers are smaller than letters.
1. For strings/characters, uppercase is smaller than lowercase.

35
Q
jshell> Arrays.compare(new int[]{1, 2}, new int[] {1})
$1 ==> 1

jshell> Arrays.compare(new int[]{1, 2}, new int[] {1, 2})
$2 ==> 0

jshell> Arrays.compare(new String[] {"a"}, new String[] {"aa"})
$3 ==> -1

jshell> Arrays.compare(new String[] {"a"}, new String[] {"A"})
$4 ==> 32

jshell> Arrays.compare(new String[] {"a"}, new String[] {null})
$5 ==> 1

System.out.println(Arrays.compare(new int[] {1}, new String[] {"a"})); // DOES NOT COMPILE
A
  1. The first element is the same, but the first array is longer.
  2. Exact match
  3. The first element is a substring of the second.
  4. Uppercase is smaller than lowercase.
  5. null is smaller than a letter.
36
Q

mismatch()

A

If the arrays are equal, mismatch() returns -1.
Otherwise, it returns the first index where they differ.

37
Q
System.out.println(Arrays.mismatch(new int[] {1}, new int[] {1}));
System.out.println(Arrays.mismatch(new String[] {"a"}, new String[] {"A"}));
System.out.println(Arrays.mismatch(new int[] {1, 2}, new int[] {1}));
A
  • In the first example, the arrays are the same, so the result is -1.
  • In the second example, the entries at element 0 are not equal, so the result is 0.
  • In the third example, the entries at element 0 are equal, so we keep looking. The element at index 1 is not equal. Or more specifically, one array has an element at index 1, and the other does not. Therefore, the result is 1.
38
Q

Equality vs. comparison vs. mismatch

A
  1. equals()
    When arrays are the same return true, else return false
  2. compare()
    When arrays are the same return 0, else return positive or negative number
  3. mismatch()
    When arrays are the same return -1, else zero or positive index
39
Q

VARARGS

A

variable arguments
ex:

public static void main(String... args) // varargs
40
Q

MULTIDIMENSIONAL ARRAYS

A

arrays can hold other arrays

Creating a Multidimensional Array

int[][] vars1; // 2D array
int vars2 [][]; // 2D array
int[] vars3[]; // 2D array
int[] vars4 [], space [][]; // a 2D AND a 3D array

String [][] rectangle = new String[3][2];

int[][] differentSizes = {{1, 4}, {3}, {9,8,7}};

int [][] args = new int[4][];
args[0] = new int[5];
args[1] = new int[3];
41
Q

Understanding an ArrayList

A

ArrayList can change capacity at runtime as needed.
Like an array, an ArrayList is an ordered sequence that allows duplicates.

you must have either of the following two statements in your class:

import java.util.*; // import whole package
import java.util.ArrayList; // import just ArrayList

CREATING AN ARRAYLIST

ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList(10);
ArrayList list3 = new ArrayList(list2);

ArrayList<String> list4 = new ArrayList<String>(); //Generics
ArrayList<String> list5 = new ArrayList<>();

List<String> list6 = new ArrayList<>();
ArrayList<String> list7 = new List<>(); // DOES NOT COMPILE  List is an interface and interfaces can’t be instantiated.
42
Q

ArrayList methods:

A
  1. boolean add(E element)
    void add(int index, E element)
    insert a new value in the ArrayList.
    It always returns true.
  2. boolean remove(Object object)
    E remove(int index)
    remove the first matching value in the ArrayList or remove the element at a specified index.
    This time the boolean return value tells us whether a match was removed.
    The E return type is the element that actually got removed.
  3. E set(int index, E newElement)
    changes one of the elements of the ArrayList without changing the size.
    The E return type is the element that got replaced.
  4. boolean isEmpty()
    int size()
  5. void clear()
  6. boolean contains(Object object)
  7. boolean equals(Object object)
43
Q
ArrayList list = new ArrayList();
list.add("hawk"); // [hawk]
list.add(Boolean.TRUE); // [hawk, true]
System.out.println(list); // [hawk, true]

ArrayList<String> safer = new ArrayList<>();
safer.add("sparrow");
safer.add(Boolean.TRUE); // DOES NOT COMPILE

4: List<String> birds = new ArrayList<>();
5: birds.add("hawk"); // [hawk]
6: birds.add(1, "robin"); // [hawk, robin]
7: birds.add(0, "blue jay"); // [blue jay, hawk, robin]
8: birds.add(1, "cardinal"); // [blue jay, cardinal, hawk, robin]
9: System.out.println(birds); // [blue jay, cardinal, hawk, robin]
A
44
Q

Since calling remove() with an int uses the index, an index that doesn’t exist will throw an exception. For example, birds.remove(100) throws an IndexOutOfBoundsException.

A
45
Q
15: List<String> birds = new ArrayList<>();
16: birds.add("hawk"); // [hawk]
17: System.out.println(birds.size()); // 1
18: birds.set(0, "robin"); // [robin]
19: System.out.println(birds.size()); // 1
20: birds.set(1, "robin"); // IndexOutOfBoundsException
A
46
Q

WRAPPER CLASSES

A
  1. Primitive type: boolean
    Wrapper class: Boolean
    Ex: Boolean.valueOf(true)
  2. Primitive type: byte
    Wrapper class: Byte
    Ex: Byte.valueOf((byte) 1)
  3. Primitive type: short
    Wrapper class: Short
    Ex: Short.valueOf((short) 1)
  4. Primitive type: int
    Wrapper class: Integer
    Ex: Integer.valueOf(1)
  5. Primitive type: long
    Wrapper class: Long
    Ex: Long.valueOf(1)
  6. Primitive type: float
    Wrapper class: Float
    Ex: Float.valueOf((float) 1.0)
  7. Primitive type: double
    Wrapper class: Double
    Ex: Double.valueOf(1.0)
  8. Primitive type: char
    Wrapper class: Character
    Ex: Character.valueOf('c')
47
Q
int primitive = Integer.parseInt("123");
Integer wrapper = Integer.valueOf("123");

int bad1 = Integer.parseInt("a"); // throws NumberFormatException
Integer bad2 = Integer.valueOf("123.45"); // throws NumberFormatException
A
48
Q

Converting String to a primitive
Converting String to a wrapper class

A

1. Boolean

Boolean.parseBoolean("true") // Converting String to a primitive
Boolean.valueOf("TRUE") // Converting String to a wrapper class

2. Byte

Byte.parseByte("1") 
Byte.valueOf("2")

3. Short

Short.parseShort("1")
Short.valueOf("2")

4. Integer

Integer.parseInt("1")
Integer.valueOf("2")

5. Long

Long.parseLong("1") 
Long.valueOf("2")

6. Float

Float.parseFloat("1")
Float.valueOf("2.2")

7. Double

Double.parseDouble("1")
Double.valueOf("2.2")

8. Character

None 
None
49
Q

One advantage of a wrapper class over a primitive is that because it’s an object, it can be used to store a null value. While null values aren’t particularly useful for numeric calculations, they are quite useful in data-based services. For example, if you are storing a user’s location data using (latitude,longitude), it would be a bad idea to store a missing point as (0,0) since that refers to an actual location off the coast of Africa where the user could theoretically be.

A
50
Q

AUTOBOXING AND UNBOXING

A

Since Java 5, you can just type the primitive value, and Java will convert it to the relevant wrapper class for you. This is called autoboxing. The reverse conversion of wrapper class to primitive value is called unboxing.

3: List<Integer> weights = new ArrayList<>();
4: Integer w = 50;
5: weights.add(w); // [50]
6: weights.add(Integer.valueOf(60)); // [50, 60]
7: weights.remove(new Integer(50)); // [60]
8: double first = weights.get(0); // 60.0
3: List<Integer> heights = new ArrayList<>();
4: heights.add(null);
5: int h = heights.get(0); // NullPointerException
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.remove(1);
System.out.println(numbers);
51
Q

turning an ArrayList into an array:

13: List<String> list = new ArrayList<>();
14: list.add("hawk");
15: list.add("robin");
16: Object[] objectArray = list.toArray();
17: String[] stringArray = list.toArray(new String[0]);
18: list.clear();
19: System.out.println(objectArray.length); // 2
20: System.out.println(stringArray.length); // 2
A
  • Line 16 shows that an ArrayList knows how to convert itself to an array. The only problem is that it defaults to an array of class Object. This isn’t usually what you want.
  • Line 17 specifies the type of the array and does what we actually want. The advantage of specifying a size of 0 for the parameter is that Java will create a new array of the proper size for the return value. If you like, you can suggest a larger array to be used instead. If the ArrayList fits in that array, it will be returned. Otherwise, a new one will be created.
  • Also, notice that line 18 clears the original List. This does not affect either array. The array is a newly created object with no relationship to the original List. It is simply a copy.
52
Q

create backed List:

20: String[] array = { "hawk", "robin" }; // [hawk, robin]
21: List<String> list = Arrays.asList(array); // returns fixed size list
22: System.out.println(list.size()); // 2
23: list.set(1, "test"); // [hawk, test]
24: array[0] = "new"; // [new, test]
25: System.out.print(Arrays.toString(array));// [new, test]
26: list.remove(1); // throws UnsupportedOperationException
A

create a List that is linked to the original array.
When a change is made to one, it is available in the other.
It is a fixed-size list and is also known as a backed List because the array changes with it.

  • Line 21 converts the array to a List. Note that it isn’t the java.util.ArrayList we’ve grown used to. It is a fixed-size, backed version of a List.
  • Line 23 is okay because set() merely replaces an existing value. It updates both array and list because they point to the same data store.
  • Line 24 also changes both array and list.
  • Line 25 shows the array has changed to [new, test].
  • Line 26 throws an exception because we are not allowed to change the size of the list.
53
Q

create an immutable List

32: String[] array = { "hawk", "robin" }; // [hawk, robin]
33: List<String> list = List.of(array); // returns immutable list
34: System.out.println(list.size()); // 2
35: array[0] = "new";
36: System.out.println(Arrays.toString(array)); // [new, robin]
37: System.out.println(list); // [hawk, robin]
38: list.set(1, "test"); // throws UnsupportedOperationException
A

Another option is to create an immutable List. That means you cannot change the values or the size of the List. You can change the original array, but changes will not be reflected in the immutable List.

  • Line 33 creates the immutable List. It contains the two values that array happened to contain at the time the List was created.
  • On line 35, there is a change to the array.
  • Line 36 shows that array has changed.
  • Line 37 shows that list still has the original values. This is because it is an immutable copy of the original array.
  • Line 38 shows that changing a list value in an immutable list is not allowed.
54
Q

USING VARARGS TO CREATE A LIST

A
List<String> list1 = Arrays.asList("one", "two");
List<String> list2 = List.of("one", "two");

Both of these methods take varargs, which let you pass in an array or just type out the String values. This is handy when testing because you can easily create and populate a List on one line.
Both methods create fixed-size arrays.
If you will need to later add or remove elements, you’ll still need to create an ArrayList using the constructor.

55
Q

Array and list conversions

A
  1. Object[] toArray()
    <T> T[] toArray(T[] a)
    Not allowed to remove values from created object
    Allowed to change values in the created object
    Changing values in the created object will not affects the original or vice versa.
  2. static <T> List<T> asList(T... a) (fixed-size list/backed List)
    Not allowed to remove values from created object
    Allowed to change values in the created object
    Changing values in the created object affects the original or vice versa.
  3. static <E> List<E> of() (unmodifiable list)
    Not allowed to remove values from created object
    Not allowed to change values in the created object
    NA
56
Q

ArrayList SORTING

A
List<Integer> numbers = new ArrayList<>();
numbers.add(99);
numbers.add(5);
numbers.add(81);
Collections.sort(numbers);
System.out.println(numbers); // [5, 81, 99]
57
Q
3: Set<Integer> set = new HashSet<>();
4: System.out.println(set.add(66)); // true
5: System.out.println(set.add(66)); // false
6: System.out.println(set.size()); // 1
7: set.remove(66);
8: System.out.println(set.isEmpty()); // true
A

All the methods you learned for ArrayList apply to a Set with the exception of those taking an index as a parameter. Why is this? Well, a Set isn’t ordered, so it wouldn’t make sense to talk about the first element. This means you cannot call set(index, value) or remove(index). You can call other methods like add(value) or remove(value).

58
Q

Common Map methods

A
  1. V get(Object key)
    Returns the value mapped by key or null if none is mapped
  2. V getOrDefault(Object key, V other)
    Returns the value mapped by key or other if none is mapped
  3. V put(K key, V value)
    Adds or replaces key/value pair. Returns previous value or null
  4. V remove(Object key)
    Removes and returns value mapped to key. Returns null if none
  5. boolean containsKey(Object key)
    Returns whether key is in map
  6. boolean containsValue(Object value)
    Returns whether value is in map
  7. Set<K> keySet()
    Returns set of all keys
  8. Collection<V> values()
    Returns Collection of all values
59
Q
8: Map<String, String> map = new HashMap<>();
9: map.put("koala", "bamboo");
10: String food = map.get("koala"); // bamboo
11: String other = map.getOrDefault("ant", "leaf"); // leaf
12: for (String key: map.keySet())
13: System.out.println(key + " " + map.get(key)); // koala bamboo
A
60
Q

Calculating with Math APIs

A
  1. double min(double a, double b)
    float min(float a, float b)
    int min(int a, int b)
    long min(long a, long b)
    The max() method works the same way except it returns the larger value.
  2. long round(double num)
    int round(float num)
    gets rid of the decimal portion of the value, choosing the next higher number if appropriate. If the fractional part is .5 or higher, we round up.
  3. double pow(double number, double exponent)
    Fractional exponents are allowed as well. Sixteen to the .5 power means the square root of 16, which is 4.
  4. double random()
    returns a value greater than or equal to 0 and less than 1.