Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Im trying to understand the relationship between array, ArrayList, and List.
Say I wanted to remove duplicates by converting an array into an ArrayList then into a HashSet, then returned to an array.
int[] start = {1,2,3,4,5};
....
....
....
int[] result = .....
How would that work?
Array is a fixed length data structure. It is a continuous block of memory. Let say you have an array at x3000 with a length of 2. An array stay at x3000 and x3001. Remember, this is oversimplifying the concept, as element size and size per memory location will certainly affect the position of array's elements (not always end at x3001).
List is an abstract data type (ADT), the notable difference between list and array is list has no fixed length. There can be more differences but it may vary from case to case.
ArrayList is a ADT list, but implemented using array. It's like when you do problems that require constructing stack, queue, etc using array.
int[] array = {1, 2, 3, 4, 5};
for(int i : array) {
System.out.print(i+", ");
}
System.out.println();
ArrayList myArrayList = new ArrayList();
for(int num : array) {
myArrayList.add(num);
}
System.out.println(myArrayList);
HashSet<Integer> myHashSet = new HashSet<Integer>();
for(int i = 0;i<myArrayList.size();i++) {
myHashSet.add((Integer) myArrayList.get(i));
}
System.out.println(myHashSet);
This is an example of a normal int array converted to an ArrayList converted to a HashSet.
the relationship between array, ArrayList, and List.
An array is created with the [] and {} notation you showed in your question. It's not dynamically allocated.
A List is an interface, which is just a guide to what methods its implementations must respond to.
An ArrayList is an implementation of a List.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How might I convert List<List<String>> to String[][]?
I've played around with the solutions provided here but not having much luck.
Any help would be appreciated.
Explanation
You can not just apply outer.toArray(...) because that would give you an array of lists, List<String>[].
You have to first convert all the inner lists before you can collect them into your resulting data structure. There is no utility method available that can do this automatically for you, but it is fairly easy to do it yourself.
Stream API
Streams are a very good candidate for this. Just stream the outer list, convert the inner lists and then use toArray as provided by Stream.
String[][] result = outer.stream() // Stream<List<String>>
.map(inner -> inner.toArray(String[]::new)) // Stream<String[]>
.toArray(String[][]::new);
Traditional loop
You can follow the exact same idea also with a more traditional manual approach where you setup your target outer array, loop over the inner lists, convert them and collect them into your array.
String[][] result = new String[outer.size()];
int i = 0;
for (List<String> inner : outer) {
result[i] = inner.toArray(String[]::new);
i++;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Note: This question is for my assignment. So there are some rules which might seem to be not normal.
I just realized my question before doesn't make sense. So I edited it.
Assume that I have a list containing integers [1,2,3,4,1,2,1,5]
By using an iterator, how can I remove duplicated items while keeping the order of items undisrupted?
The expected result for above list should be [1,2,3,4,5]
And contain() method is not allowed to use.
What I currently came up with is the same as what Manash Ranjan Dakua answered in this question
How do I remove repeated elements from ArrayList?
public static void main(String[] args){
ArrayList<Object> al = new ArrayList<Object>();
al.add("abc");
al.add('a');
al.add('b');
al.add('a');
al.add("abc");
al.add(10.3);
al.add('c');
al.add(10);
al.add("abc");
al.add(10);
System.out.println("Before Duplicate Remove:"+al);
for(int i=0;i<al.size();i++){
for(int j=i+1;j<al.size();j++){
if(al.get(i).equals(al.get(j))){
al.remove(j);
j--;
}
}
}
System.out.println("After Removing duplicate:"+al);
}
But if I wish to use Iterator instead of for loops here? How can I achieve that(remove duplicated items while keeping order unchanged)?
If the question is not clear enough or too vague. Pls point out! I'll try to rephrase it.
Thanks for help!
You don't need to use Iterator to achieve that. A simple way is using LinkedHashSet which allows to contain unique elements only like HashSet (No Duplicates) and maintains insertion order.
Example:
List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,1,2,1,5));
Set<Integer> set = new LinkedHashSet<>();
set.addAll(list);
// or as suggested by assylias, Set<Integer> set = new LinkedHashSet<>(list);
System.out.println(list);
System.out.println(set);
Output:
[1, 2, 3, 4, 1, 2, 1, 5]
[1, 2, 3, 4, 5]
You can simply call .next() again which will allow you to move on to the next element in the array. However if you want to get a new iterator for the rest of the elements, it would be best for you to use .next() through the rest of the list you have, adding each element to a new data structure and then call .iterator() on that new data structure.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Set<ArrayList<Integer>> hs = new HashSet<ArrayList<Integer>>();
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
hs.add(arr);
ArrayList<Integer> arr1 = new ArrayList<Integer>();
arr1.add(4);
arr1.add(3);
arr1.add(2);
arr1.add(1);
hs.add(arr1);
System.out.println(hs.size());
The output I get is 2. I want to get 1 as both the arrayLists have the same elements. How can I achieve this?
In the second block, after creating arr1, you add the number 1 to 3 to arr again. Obviously, an ArrayList with 8 elements isn't equal to an empty ArrayList, so you'd have two members in the HashSet. If you fix the code to add the same elements to arr1, you'll get a HashSet with a size of 1.
In the code you pasted, you are adding 1, 2, 3, and 4 to the first list (arr) twice, and adding nothing to the second list (arr1). Thus arr1.equals(arr) is going to be false.
Fix the typo in your code so that arr1 contains the same elements as arr, and you will achieve your goal.
Even if the contents are same, both arraylists are different objects. You are bound to see 2 elements in the set.
Its like having two employees with exactly the same name.
Not sure if you can implement equals method for arraylists.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Why do we need two-dimensional or multi-dimensional array?
If we want a series of continuous elements of the same type, it can be achieved with simple 1-D array. Like int[] a = new int[15625] will allocate space 15625 elements, and
int [][][] b = new int[25][25][25] will also allocate space 15625 elements
Why do we need them if things can be achieved with 1-d?
You don't need them, but doing grid[x][y] is nicer than grid[x + y*width]
Because sometimes data isn't one dimensional.
For example, the classic game breakout. You could organize your bricks into a one dimensional array and each turn process which row they are in, however it makes more sense to make it a two-dimensional array where the first array is the rows, and the second array is the bricks.
i.e:
bricks[0][3] is the fourth brick of the rirst row
While this could still be done with a one dimensional array, there are math applications where multi-dimensional arrays are necessary.
In addition to this it allows you to have arrays of an infinite1. size, whereas arrays are limited to 230
1. mileage may vary
As mentioned in the comments, multi-dimensional arrays in Java are actually nested arrays. Your nested arrays don't all need to be the same size which is one reason you would use them instead of a single array as you have proposed.
The only other way to declare such an array (off the top of my head) is to declare an array of type Object and then put arrays in it but you lose the basic array type safety. You can access the elements in nested arrays without the [][]... syntax, however.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have the following List:
private String[] myArray = new String[]{"A","B","C"} ;
List myList = new ArrayList();
for (int i = 0; i < myArray.length; i++) {
myList.add(myArray[i]);
}
There is a method that returns an element of the myList
String returnValue=myMethod();
returnValue could be A or B or C
returnValue should be the first element of the List
myList.add(0, returnValue);
Issue is if returnValue="B" ,myList becomes {"B","B","C"}.
I could explicitly remove the returnValue and add it again to myList. But it seems rather redundant ,can anybody suggest a better design approach.
My Required Result would be {"B","A","C"}
As far as I understood, you want the returnValue to become the first element of the List, i.e. change the order.
This can be achieved by using:
Collections.swap(myList, 0, myList.indexOf(returnValue));
Since this does not use adding nor removing, it allows to simplify your entire code:
List<String> myList = Arrays.asList("A","B","C");
String returnValue=myMethod();
Collections.swap(myList, 0, myList.indexOf(returnValue));
Note that this changes the order of the remaining elements. If you want to retain the order of all elements but the one you move to the front of the list (like remove followed by add would do) you need to use rotate:
List<String> myList = Arrays.asList("A","B","C");
String returnValue=myMethod();
Collections.rotate(myList.subList(0, myList.indexOf(returnValue)+1), 1);
But using swap will be faster on large lists, so if you don’t need the remaining elements to retain the original order, using swap is recommended.
List.add(index, element) doesn't replace the first element in your List, it inserts and thereby it moves all the following elements. You would end up with 4 entries in your list:
{RETURNVALUE, "A","B","C"}
There's also a replacing variant: List.set(index, element). With that you would end uo with 3 entries in your list:
{RETURNVALUE,"B","C"}
If you want to keep your List all sorted, there's the simple utility method
Collections.sort(mylist);
that sorts your collection in respect of it's element's compareTo() method, which would be a simple String ordering in your case.
If your RETURNVALUE is B and you've inserted the element, you would end up with
{"A","B","B","C"}
If I good understand your problem, you should use set(int index, E element) method to replace given element in your list