So a part of my homework is to get a string of integer numbers and put each one of them in a list, this is what I have done:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String N;
int count;
LinkedList<Integer> booksList = new LinkedList<>();
System.out.printf("Give: ");
N = input.nextLine();
String[] arr = N.split(" ");
for (count = 0; count < arr.length - 2; count++) {
booksList.add(Integer.parseInt(arr[count + 2]));
}
So what I’ve done is take the string, split it into an array and then take the items with the for loop and put them into a list. What I am confused with is that I see people using the add command with a “new” inside the parentheses like this:
booksList.add(new Integer.parseInt(arr[count + 2]));
This is confusing me and I’m not totally sure if I’m doing this the right way.
By the way, I take the array elements from count + 2 because I do not need the first two elements of the answer but I need to store the first two integers in two separate variables.
Also I’ve seen some people write this:
List<Integer> booksList = new LinkedList<>();
Is there any difference from that and what I’ve written?
The construct
is often seen for mainly 2 reasons:
Very often you just do iterate over the collection, use a for loop, search, sort, put into, take from, delete.
If you find out, that a sibling of your first thought is better suited, you can later change the RHS, without need to rewrite the rest of your program, because, for example, most methods of LinkedList and ArrayList fullfill the same contract, defined in List.
But for sorting, searching and so on List is well suited. Have a look at the documentation, and compare List, LinkedList and ArrayList. Try to replace the one with another in your code.
Maybe two ‘sublist (int fromIndex, int toIndex)’ methods, in Linked~ and ArrayList are defined in the base class, and behave identically.
But maybe they are specialized, and implement subList on their own. Here we have a Interface <- Class relationship, so we know, that there is no implementation in the Interface, it is completly abstract. But in the case of (Abstract) base classes <- derived classes the pattern is the same.
Derived/implementing classes share the same interface, ‘public List sublist (int fromIndex, int toIndex)’. You expect them to produce the same result, but in different ways – maybe.
Only if you need to call a method which is only present in, say LinkedList, you either declare your bookList as LinkedList up front, or you cast it for that purpose:
Sidenote: Your code can be simplified with the modern (7 years old) foreach-loop:
But if you declare a Scanner, you can take Integers from the Scanner directly:
In reaction to the comments, here is a third code: Reading from System.in a line, and then creating a Scanner on that that line: