How does a ArrayList’s contains() method evaluate objects?
ArrayList implements the List Interface. If you look at the Javadoc for List at the contains method you will see that it uses the equals() method to evaluate if two objects are the same.
ArrayList implements the List Interface. If you look at the Javadoc for List at the contains method you will see that it uses the equals() method to evaluate if two objects are the same.
I’m pretty sure the static frequency-method in Collections would come in handy here: int occurrences = Collections.frequency(animals, “bat”); That’s how I’d do it anyway. I’m pretty sure this is jdk 1.6 straight up.
Since Gson 2.8.0, you can use TypeToken#getParameterized(Type rawType, Type… typeArguments) to create the TypeToken, then getType() should do the trick. For example: TypeToken.getParameterized(ArrayList.class, myClass).getType()
If you are using java-8 there’s also another way to do this. int[] arr = list.stream().mapToInt(i -> i).toArray(); What it does is: getting a Stream<Integer> from the list obtaining an IntStream by mapping each element to itself (identity function), unboxing the int value hold by each Integer object (done automatically since Java 5) getting the … Read more
In Java 8 or later: String listString = String.join(“, “, list); In case the list is not of type String, a joining collector can be used: String listString = list.stream().map(Object::toString) .collect(Collectors.joining(“, “));
You can use Files#readAllLines() to get all lines of a text file into a List<String>. for (String line : Files.readAllLines(Paths.get(“/path/to/file.txt”))) { // … } Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files You can use String#split() to split a String in parts based on a regular expression. for (String part … Read more
Either: Foo[] array = list.toArray(new Foo[0]); or: Foo[] array = new Foo[list.size()]; list.toArray(array); // fill the array Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way: List<Integer> list = …; int[] array = new int[list.size()]; for(int i = 0; i < list.size(); i++) array[i] = … Read more
Use like this. List<String> stockList = new ArrayList<String>(); stockList.add(“stock1”); stockList.add(“stock2”); String[] stockArr = new String[stockList.size()]; stockArr = stockList.toArray(stockArr); for(String s : stockArr) System.out.println(s);
Collections.sort(testList); Collections.reverse(testList); That will do what you want. Remember to import Collections though! Here is the documentation for Collections.
Quite a few problems with your code: On Arrays.asList returning a fixed-size list From the API: Arrays.asList: Returns a fixed-size list backed by the specified array. You can’t add to it; you can’t remove from it. You can’t structurally modify the List. Fix Create a LinkedList, which supports faster remove. List<String> list = new LinkedList<String>(Arrays.asList(split)); … Read more