Java: ArrayList^2 to int[][] - java

I have this arrayList:
ArrayList<ArrayList<Integer>> temporary = new ArrayList<ArrayList<Integer>>();
Some how I need to convert it to a int[][]
I have some sort of loop right?
for(ArrayList<Integer> item: temporary) {
//Here??
}
Cheers!
Im stuck because arrays arent dynamic(or what you call it).

This should work:
final int N = temporary.size();
int[][] a = new int[N][];
for (int i = 0; i < N; ++i) {
final ArrayList<Integer> item = temporary.get(i);
final int M = item.size();
a[i] = new int[M];
for (int j = 0; j < M; ++j) {
a[i][j] = item.get(j); // assumes no null elements!
}
}

If you are able to make do with an Integer[][] (object wrapper of int) you can do it in a single loop (there is an inner loop, but its hidden from you).
ArrayList<ArrayList<Integer>> temporary = new ArrayList<ArrayList<Integer>>();
Integer[][] integers = new Integer[temporary.size()][];
int i = 0;
for(ArrayList<Integer> l : temporary)
{
integers[i++] = l.toArray(new Integer[l.size()]);
}

Related

Returning a single array to a multidimensional array

Full disclosure; I needed to know this for an assignment. I wanted to return a single array to a multidimensional array from a method. I circumvented the issue with the below code by returning it to another 1-dimensional array then using a for loop to transfer values.
public class test
{
public static void main ( String args[] )
{
int[][] array1 = new int [100][5];
int[] temp = new int [5];
int num = 0;
temp = setValue();
for (int i = 0; i<=4; i++) // cycle 1
{
array1[num][i]= temp[i];
}
System.out.format("\n\n");
}
public static int[] setValue()
{
int[] array3 = new int [5];
for (int i = 0; i<=4; i++)
{
array3[i]= 2;
}
return array3;
}
}
Is there a more conventional way to return array3 to array1 without cycle 1? Something along the lines of
array1[num][] = setValue();
Comments:
The method returns a new array, so no need to initialize temp, or better yet, initialize it to return value:
int[] temp = setValue();
Java doesn't have 2D arrays, just arrays of arrays, so the entire inner array can be replaced, instead of copying values:
for (int i = 0; i <= 4; i++) // cycle 1
{
array1[num] = temp;
}
When you do that, you shouldn't allocate the inner arrays, i.e. replace [5] with []:
int[][] array1 = new int[100][];
Now there is actually no need for temp anymore, leaving main as just:
int[][] array1 = new int[100][];
int num = 0;
array1[num] = setValue();
Since you probably want to fill the entire 2D array:
int[][] array1 = new int[100][];
for (int num = 0; num < array1.length; num++) {
array1[num] = setValue();
}
As #VinceEmigh hinted above you can simply do array1[num] = setValue();
see
int arr[][] = new int[5][];
for (int x = 0; x < arr.length; x++) {
arr[x] = setValue();
}
for (int x = 0; x < arr.length; x++) {
for (int y = 0; y < arr[x].length; y++) {
System.out.println(arr[x][y]);
}
}

Find Common Elements between two Arrays

I want to find the common elements between two arrays with different sizes and put them in another array.
Can you tell what's wrong with my code?
public static int[] numratEQelluar(int[] vargu, int[]varguPer)
{
int count = 0;
int [] nrQelluar = new int[count];
for(int i = 0; i<vargu.length; i++)
{
for(int idx = 1;idx<varguPer.length ; idx++)
{
if(vargu[i] == (varguPer[idx]))
{
count++;
for(int index = 0; index<nrQelluar.length; index++)
{
nrQelluar[index] = vargu[i];
}
}
}
}
return nrQelluar;
The reason it doesn't work is indeed due to incorrect memory allocation to nrEqualler as been said in the comments.
However, there are a few thing i'd change in your code:
using a LinkedList instead of primitive int [] for dynamic sized
array is much more efficient (add in O(1)).
less indentations and confusing indexes by extracting methods.
So this should do:
public static int[] numratEQelluar(int[] vargu, int[]varguPer){
List<Integer> nrQelluar = new LinkedList<Integer> ();
for(int i = 0; i < vargu.length; i++) {
if (contains(varguPer, vargu[i])) nrQelluar.add(vargu[i]);
}
return toPrimitive(nrQelluar);
}
private static boolean contains(int [] array, int num){
for(int i = 0; i < array.length; i++){
if(array[i] == num) return true;
}
return false;
}
private static int[] toPrimitive(List<Integer> list) {
int[] primitiveArray = new int[list.size()];
for(int i = 0; i < list.size(); i++){
primitiveArray[i] = list.get(i);
}
return primitiveArray;
}
The problem is between these lines of code
int count = 0;
int [] nrQelluar = new int[count];
The size of your new array will be zero. try changing this to the sum of the length of both the arrays.
Updated with a working code.
Try this code :
public static Integer[] findCommonElements(int[] arr1, int[] arr2){
HashSet set = new HashSet<>();
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i] == arr2[j]){
set.add(arr1[i]);
}
}
}
Integer[] resultArray = (Integer[]) set.toArray(new Integer[set.size()]);
return resultArray;
}
Using a set will ensure that you won't get any duplicates in the resulting array. If duplicates are fine, then you can use ArrayList to store the common elements and then convert them into Array.

Adding Integers to ArrayList<Integer>

I have an ArrayList of LinkedLists (an array of linked lists). The LinkedLists contains integers (Integer).
private List<LinkedList> buckets;
buckets = new ArrayList<LinkedList>();
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
buckets.add(temp);
}
I later want to remove the items from the linked list (in the order they were added) and add them to an array list. When I try this:
ArrayList<Integer> sorted = new ArrayList<Integer>(unsorted.size());
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
sorted.add(buckets.get(j).removeLast());
// sorted.add((Integer)buckets.get(j).removeLast());
}
}
I get an error saying:
add(java.lang.Integer) in ArrayList cannot be applied to (java.lang.Object)
But when I cast it to an Integer (the commented out line), the array is full of null values. Anyone see what I am doing wrong?
Here is where I am adding items to bucket:
for (int i = 0; i < unsorted.size(); i++) {
int digit = (unsorted.get(i) / position) % 10;
buckets.get(digit).add(unsorted.get(i));
}
Note that sorted is an ArrayList<Integer>. When I trace it in debug mode, I can see that the LinkedLists have Integer objects with the correct values.
Screenshot of buckets contents:
Working Example:
class Ideone {
private static List<LinkedList<Integer>> buckets;
public static void main (String[] args) throws Exception {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(6);
arr.add(8);
arr.add(1);
arr.add(3);
arr.add(9);
System.out.println(arr);
arr = sort(arr);
System.out.println(arr);
}
public static ArrayList<Integer> sort(ArrayList<Integer> unsorted) {
buckets = new ArrayList<LinkedList<Integer>>();
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
buckets.add(temp);
}
ArrayList<Integer> sorted = new ArrayList<Integer>(unsorted.size());
for (int i = 0; i < unsorted.size(); i++) {
int digit = unsorted.get(i) % 10;
buckets.get(digit).add(unsorted.get(i));
}
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
sorted.add(buckets.get(j).poll());
// sorted.add((Integer)buckets.get(j).removeLast());
}
}
return sorted;
}
}
You are using the raw form of LinkedList here:
private List<LinkedList> buckets;
Because of this, removeLast will return Object, not Integer. Try
private List<LinkedList<Integer>> buckets;
and
buckets = new ArrayList<LinkedList<Integer>>();
Casting the return of removeLast to Integer was the pre-generics way of getting this to work. However, you never inserted any items into each LinkedList, so removeLast returns null. If you want something returned, first insert something into each LinkedList that gets inserted into buckets.
Casting to Integer would still work, but supplying Integer as the type argument to LinkedList is preferred, especially since you are using generics by supplying LinkedList as the type parameter to List already.
In your nested loop,
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
// ***** here *****
sorted.add(buckets.get(j).poll());
}
}
You look to be polling the wrong List.
Try changing
sorted.add(buckets.get(j).poll());
to:
sorted.add(buckets.get(i).poll());
Perhaps a cleaner more intuitive way to code this would be something like:
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (int j = 0; j < innerList.size(); j++) {
sorted.add(innerList.poll());
}
}
Although this may not work if the innerList has multiple items. Why not instead remove items safely with an iterator?
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (Iterator<Integer> iterator = innerList.iterator(); iterator.hasNext();) {
sorted.add(iterator.next());
iterator.remove(); // this guy is optional
}
}
Either that or simply use get(j)
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (int j = 0; j < innerList.size(); j++) {
sorted.add(innerList.get(j));
}
}
Although this isn't efficient use of a LinkedList
The item that you inserted into the ArrayList "sorted" is the item you took from the link list LinkedList.
But you never actually add any item to it. You simply just created a LinkedList and added it to your bucket list.
You need to add something into the temp list.
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
// Add something to the temp LinkedList
buckets.add(temp);
}

Need Help Adding an Integer Array to an Array List in Processing

Ok... So I am in the middle of a project, and I've hit a bit of a wall. If anyone could please explain how to add an integer array to an ArrayList of integer Arrays, I would greatly appreciate it. This is in processing, the javascript version more specifically. I have tested and everything works right up to 'symbols.get(i).add(tempArray). If I print tempArray right before that line it gives me '6 10 16 10 16 20', as it should. And no, it's not just the println(symbols) statement, I also tried just 'println("blah");'and that did not show up in the output, so something is going awry at the .get line.
size(850,250);
String[] myList = new String[100];
ArrayList<Integer[]> symbols = new ArrayList<Integer[]>();
int[] tempArray = new int[];
String numbers = ("6,10,16,10,16,20\n1,25,21,13,3,15\n6,5,20,6,21,20");
myList = (split(numbers, "\n"));
int j = myList.length();
for(int i = 0; i<j; i++)
{
tempArray = int(split(myList[i], ','));
symbols.get(i).add(tempArray);
}
println(symbols);
... I have also tried the following in place of 'symbols.get(i).add(tempArray);'
for(int a = 0; a < tempArray.length(); a++)
{
symbols.get(i[a]) = tempArray[a];
}
println(symbols);
... I have also tried
for(int a = 0; a < tempArray.length(); a++)
{
symbols.get(i) = tempArray[a];
}
println(symbols);
... and
for(int a = 0; a < tempArray.length(); a++)
{
symbols[i][a] = tempArray[a];
}
println(symbols);
I'm out of guesses and tries, any help would be appreciated.
First get the Array of integer by using the get method on the ArrayList, then add [index] to specify what to add at which index of the returned Array.
symbols.get(i)[a] = tempArray[a];
There are some mistakes. The key one is that you can't add int[] to the list expecting Integer[]. Here, see the comments on the code:
void setup()
{
size(850, 250);
String[] myList = new String[100];
ArrayList<Integer[]> symbols = new ArrayList<Integer[]>();
// you can't init an array without a inintial dimension
//int[] tempArray = new int[];
int[] tempArray;
String numbers = ("6,10,16,10,16,20\n1,25,21,13,3,15\n6,5,20,6,21,20");
myList = (split(numbers, "\n"));
//length is not a method... no parenthesis here
//int j = myList.length();
int j = myList.length;
for (int i = 0; i<j; i++)
{
tempArray = int(split(myList[i], ','));
// you cant add an int[] to an Integer[] arrayList
// you gotta either change the arraylist type or convert the ints to Integers
// also just use .add(). not get().add() it's a one dimension list
symbols.add(parseArray(tempArray));
println(symbols.get(i) );
println("--");
}
}
//convenience function..
Integer[] parseArray(int[] a) {
Integer[] b = new Integer[a.length];
for (int i = 0; i<a.length; i++) {
b[i] = Integer.valueOf(a[i]);
}
return b;
}
and the other way...
void setup()
{
size(850, 250);
String[] myList = new String[100];
ArrayList<int[]> symbols = new ArrayList<int[]>();
// you can't init an array without a inintial dimension
//int[] tempArray = new int[];
int[] tempArray;
String numbers = ("6,10,16,10,16,20\n1,25,21,13,3,15\n6,5,20,6,21,20");
myList = (split(numbers, "\n"));
//length is not a method... no parenthesis here
//int j = myList.length();
int j = myList.length;
for (int i = 0; i<j; i++)
{
tempArray = int(split(myList[i], ','));
symbols.add(tempArray);
println(symbols.get(i) );
println("--");
}
}

How divide 2d array into 1d array by one statement?

If I have:
int[] a = {1,2,3,4,5};
int[] b = {5,7,8,9};
int[][] array2d ={a,b};
I can divide array2d into 2 1d array by:
int[] A = new int[array2d[0].length];
int[] B = new int[array2d[1].length];
for(int i = 0; i < array2d.lenght; i++){
A[i] = array2d[i][0];
B[i] = array2d[i][1];
}
but can it be done by one statement?
For example if I have:
int[][] array2dx = new int[2][1000];
I can do easy:
int[] Ax = array2dx[0];
int[] Bx = array2dy[1];
So I am look for something similar (dividing into 2 arrays) for array int[1000][2];
but can it be done by one statement?
Not with any built-in methods that I'm aware of. It sounds like you basically want to write a transpose method though:
static int[][] transpose(int[][] input) {
// TODO: Validation. Detect empty and non-rectangular arrays.
int[][] ret = new int[input[0].length][];
for (int i = 0; i < ret.length; i++) {
ret[i] = new int[input.length];
}
for (int i = 0; i < input.length; i++) {
for (int j = 0; i < ret.length; j++) {
ret[j][i] = input[i][j];
}
}
return ret;
}
Once you've transposed an int[1000][2] into an int[2][1000] you can get the two int[1000] arrays out simply, as you've already shown.

Categories