Addressing multi-dimensional arraylists - java

I'm attempting a radix sort but I'm having trouble addressing arraylists of arraylists. The list has 10 spaces, each with a bucket of size n.
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(10);
ArrayList<Integer> bucket = new ArrayList<>();
bucket.add(99);
list.add(bucket);
list.add(bucket);
list.get(0).add(12); (6)
When I attempt to add in a value using (6) it adds 12 for each arraylist within list (presumably because they are both buckets). How can I initialize the arraylist properly such that I treat each arraylist in list independently? And would I access the elements of each arraylist in list in a similar fashion?

I think what you're looking for is
for (int i = 0; i < 10; i++) {
list.add(new ArrayList<>());
}
You can set a size for each bucket if you want also - I think by passing the desired size to the ArrayList constructor

When you add 12 to the ArrayList in list, you are adding to a referenced ArrayList, which in this case is bucket. list.get(0) and list.get(1) will both return a reference to the same ArrayList, bucket.

Related

Is there a way to put all the values of a HashMap in an array?

I have a HashMap, let's say, with entries {1=1, 3=2, 4=1, 5=1, 6=1} . I'd like to be able to create an array just containing [1,2,1,1,1]. Is that possible?
To give some context, I'm trying to get something I can iterate over using an index, and anything like an array or ArrayList would work (the order of the items does matter).
I tried assigning the values to an array using
for (int j=0; j< frequencies.size(); j++){
for (int i : frequencies.values()) {
arr[j] = i;
}
}
frequencies.values() (frequencies is the name of my HashMap) wasn't of particular use, and I tried both iterating over that (didn't work) and assigning it to Collections wasn't useful. I tried assigning myHashMap.values() to an ArrayList as well, which obviously didn't work.
What would you recommend?
The type of frequencies.values() is a generic Collection, not necessarily an ArrayList. As a result, to convert it to an ArrayList, you must copy it -- fortunately, ArrayList has a constructor that accepts a generic Collection and copies it. As a result, all you have to do is write new ArrayList<>(frequencies.values()).
Is there a way to put all the values of a HashMap in an array?
Since you did specify an array as the target you can do it like this.
Map<Integer,Integer> map = new HashMap<>(Map.of(1,1,3,2,4,1,5,1,6,1));
int[] vals = map.values().stream().mapToInt(Integer::valueOf).toArray();
System.out.println(Arrays.toString(vals));
Prints
[1, 2, 1, 1, 1]
This is a kinda hacky way but it works well for me.... it assumes the values of the numbers from your hashmap are Longs.
Collect the values from your "frequencies" hashmap:
1. Collection<Long> values_from_hashmap = frequencies.values();
Create an array list from the collection of values:
2. ArrayList<Long> listOfValues = new ArrayList<Long>(values_from_hashmap);
Boom your listOfValues array list will contain the values from the orig hashmap

How do I reorder a doubly linked list to match the order of an array with the same elements?

I am trying to update the order of my doubly linked list based on an array with the same elements in the updated order.
For example if I have:
cat->dog->rabbit->panda
And I want to reorder to have the order of the array:
String[] pets = {"dog", "rabbit", "panda", "cat"};
For context: I am new to Java and programming in general so not sure how to do so. Essentially, what I am doing is that I shuffled the elements of a seating arrangement and the doubly linked list is a non-shuffled version of those students. I just want to update the doubly linked list to match the order of the new shuffled version. I want a function that can do so.
I have methods to access the last and first elements of the doubly linked list and the ability to go left or right from one element. I want to do this with elementary knowledge, without using maps and stuff. Sorry if it sounds like a hassle, I just want to understand what's happening!
If your linked list class has the same operations as a standard LinkedList, you can create a map of pets to their indices in the array:
Map<String, Integer> arrayIndices =
IntStream.range(0, pets.length)
.boxed()
.collect(Collectors.toMap(i -> pets[i], i -> i));
Then sort the list with a custom comparator that sorts by array index:
linkedList.sort(Comparator.comparing(arrayIndices::get));
Instead of creating a mam and then comparing, I would declare an array with the order expected:
String[] order = {"cat","dog","rabbit","panda"};
Then I would trace a sorting algorithm, here is an example (very simple one):
for (int i=0; i < pets.length(); i++){
for (int k=0, k < order.length(); k++){
if (pets[i] == order[k]){
if (i != k){
String store = pets[k];
pets[k] = pets[i];
pets[i] = store;
}else{
// Proper position
}
}
}
}
This takes longer to code than what markovv answered; however, you don't dive have to dive into Maps.

Type mismatch when creating List of objects

I am trying to part the mainListarraylist to 3 sublist Arraylist and then add it as sublist in other arraylist mainSublist but I am getting this error:
How can I fix it?
I appreciate any help.
1)-Type mismatch: cannot convert from List to ArrayList
2) -The method add(RootCreator) in the type ArrayList is not applicable for the arguments (ArrayList)
Code:
ArrayList<RootCreator> mainList = new ArrayList<RootCreator>();
for (String key : names) {
RootCreator rootcreat = join_line(path, key);
mainList.add(rootcreat);
}
ArrayList<RootCreator> mainSublist = new ArrayList<RootCreator>();
for(int i= 0 ; i < mainList.size(); i++){
int index = i*3;
//the error 1 is here
ArrayList<RootCreator> sublist = mainList.subList(0, index);
//error 2 is here
mainSublist.add(sublist);
}
All List are not ArrayList, so when you use sublist you get a generic List. On the other hand, the method to add a collection to another collection is addAll instead add.
List<RootCreator> mainList = new ArrayList<RootCreator>();
for (String key : names) {
RootCreator rootcreat = join_line(path, key);
mainList.add(rootcreat);
}
List<RootCreator> mainSublist = new ArrayList<RootCreator>();
for(int i= 0 ; i < mainList.size(); i++){
int index = i*3;
//the error 1 is here
List<RootCreator> sublist = mainList.subList(0, index);
//error 2 is here
mainSublist.addAll(sublist);
}
The subList method returns a List, not an ArrayList, and you cannot assign a List to an ArrayList. In fact, the List returned by the subList method is not an ArrayList.
If it needs to be an ArrayList, then create an ArrayList out of the sub list.
ArrayList<RootCreator> sublist = new ArrayList<>(mainList.subList(0, index));
If you just need a List, then make sublist a List instead.
List<RootCreator> sublist = mainList.subList(0, index);
You can't add an ArrayList<RootCreator> to an ArrayList<RootCreator>; you must add a RootCreator. If you want to add the elements of sublist to another list, then use the addAll method.
mainSublist.addAll(sublist);
OK, let's look at the two errors here:
//the error 1 is here
ArrayList<RootCreator> sublist = mainList.subList(0, index);
This is telling you that you're trying to assign something of the type List to a variable that's declared as an ArrayList. While an ArrayList is a subtype of List, it doesn't work both ways - you can assign an ArrayList to a List, but not vice versa. So let's change your declaration:
//the error 1 was here, but fixed.
List<RootCreator> sublist = mainList.subList(0, index);
The second one is slightly different:
//error 2 is here
mainSublist.add(sublist);
Here, you've got a list defined to hold items of the type RootCreator - but you're not adding RootCreator items, you're adding a list of them. So if you want to have the list hold other lists, you need to specify that when you create it:
ArrayList<List<RootCreator>> mainSublist = new ArrayList<List<RootCreator>>();
But, if you're trying to just keep a single list and want to add everything from the sublists, then instead, change your code to:
//error 2 was here, but Fixed
mainSublist.addAll(sublist);

How to make ArrayList that work as two dimentional array in java?

I want to make arrayList object in java that work as two dimentional array. My question is how can we access value from specific dimention from arrayList.
in two dimentional array, if i want to access value then it can be as m[i][j].
But in arraylist how can i do that ?
You mean something like a List in a List??
May be something like...
List<List<...>> twoDList = new ArrayList<>();
i want to make a List, in which each List key contains another List inside it
It should more like you want some kind of Map, which is basically a key/value pair.
Map<String, List<String>> mapValues = new HashMap<>(25);
List<String> listOfValues = ...;
//...
mapValues.put("A unique key for this list", listOfValues);
//...
List<String> thatListOfValues = mapValues.get("A unique key for this list");
List<List<Integer>> list = new ArrayList<List<Integer>>();
list.add(new ArrayList<Integer>());
list.add(new ArrayList<Integer>());
list.get(0).add(5);
list.get(1).add(6);
for(List<Integer> listiter : list)
{
for(Integer integer : listiter)
{
System.out.println("" + integer);
}
}
This way you can get the items like
list.get(1).get(0); //second dimension list -> integer
EDIT:
Although it is true that you can use a Map if you are trying to use numeric indices for example for each list, like so:
Map<Integer, List<YourObject>> map = new HashMap<Integer, List<YourObject>>();
map.put(0, new ArrayList<YourObject>());
map.put(5, new ArrayList<YourObject>());
map.get(0).add(new YourObject("Hello"));
map.get(5).add(new YourObject("World"));
for(Integer integer : map.keySet())
{
for(YourObject yourObject : map.get(integer))
{
yourObject.print(); //example method
System.out.println(" ");
}
}
Although even then the accessing of Lists would be the same as before,
map.get(0).get(1); //List -> value at index
Obviously you don't need to use Integers as the generic type parameter, that's just a placeholder type.
The solution like List<List<..>> is slow then you should use one dimention array like
// Two dimentions: m and n
List<String> arr = new ArrayList<String>(m*n);
for (int i=0; i< m; ++i) {
for (int j=0; j<n; ++j) {
String str=arr.get(i*n + j);
//You code here
}
}
Memory is an important consideration here.
It can be acceptable to model a 2D (or higher dimension) array using a 1D container. (This is how the VARIANT SAFEARRAY of Microsoft's COM works.) But, consider this carefully if the number of elements is large; especially if the container allocates a contiguous memory block. Using something like List<List<... will model a jagged-edged matrix and can fragment your memory.
With the 1D approach, you can use the get(index) method on the ArrayList appropriately transformed:
Given the (i)th row and (j)th column, transform using index = i * rows + j where rows is the number of rows in your matrix.
An arraylist is not an object to make a 2 dimentional arrays. However you can use it anyway :
You can use :
new ArrayList<ArrayList<Object>>; //or
new ArrayList<Object[]>;
But you should implement your own matrix class because you will probably have some check to do and a function get(int row, int column) would be cool
Also consider Table collection provided by Google Guava library. ArrayTable is an implementation based on 2D array.
You cane define like this
1>
List<Object[]> list = new ArrayList<Object[]>();
Fetching
list.get(i)[j];
2>
List<Map<Integer,Object>> list = new ArrayList<Map<Integer,Object>>();
Fetching
list.get(i).get(j);

loading 2D arrays into a java linked list

I am a new programmer writing a sudoku program. I have guess values stored into a linked list structure. I have a method which determines where the best guess location is and then guesses all possible values for that entry.
My specific question is that when I loop thru to enter multiple guesses, the subsequent guesses overwrite the earlier guesses so I end up with guessQueue holding multiple copies of the same guess. How should I call the loading into the linked list to avoid this problem? I created a short sample method which illustrates the point here (and hopefully is SCCE):
public void TestLinkedList(){
LinkedList testQueue = new LinkedList();
int[][] testGrid = new int[9][9];
for (int k=0;k<10;k++){
for (int j=0;j<9;j++){
for (int jj=0;jj<9;jj++){
testGrid[j][jj]=k;
}
}
testQueue.addLast(testGrid);
}
}
I expect each entry in the linked list to contain an array with each value in the array 1 higher than the previous entry into the linked list, but all the values in the arrays in the linked list are the same
The Arrays class and the Collections framework can help you out:
Java Code:
T[] array= new T[ ... ];
List list= new LinkedList(Arrays.asList(array));

Categories

Resources