How to set size of two dimensional ArrayList? - java

So I'm trying to make an two dimensional ArrayList which has a set amount of ArrayLists, then each of those ArrayLists can contain as much as needed. I'm aware that arrays dynamically change size, but I'm trying to guarantee that is has at least a certain size in this case.
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>(10);
This doesn't work. I want to be able to set the location of a new Integer to one of the first dimension's indices, like so:
integers.get(7).add(new Integer(42));
This just gives me an IndexOutOfBoundsException, as though there are no Integer ArrayLists within the ArrayList. Is there a way to do this? I'm sure it's something simple I'm not seeing.

Array lists do not work like this. They are not arrays.
The list you created is backed by array of at least 10 elements, but itself it does not contain any, so you cannot refer to 7th or actually any one element.
integers.size() would return 0
integers.isEmpty() would return true
integers.get(0) would throw
Moreover, the list you initialized needs to be filled with lists themselves:
for (int i = 0; i < 10; ++i) {
row = new ArrayList<Integer>()
integers.add(row);
}
// now integers is a 10-element list of empty lists
Alternatively you could use primitive arrays (if you want to have a fixed-size rectangle).
int integers[][] = new int[10][];
for (int i = 0; i < integers.length; ++i) {
integers[i] = new int[10]; // rows are initialized to 0, as int is primitive
}
for (final int[] arr : integers) {
System.out.println(Arrays.toString(arr));
}

You can use a nested loop for this. Here is a short example:
import java.util.ArrayList;
public class PopulateArray {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>();
int num_arrays_ to_populate = 10;
int num_indices_to_populate = 10;
for(int i = 0; i < num_arrays_to_populate; i++) {
integers.add(new ArrayList<Integer>());
for(int j = 0; j < num_indices_to_populate; j++) {
integers.get(i).add(0);
}
}
}
}
This would create an ArrayList of ArrayLists of ints and fill the top ArrayList with 10 ArrayLists and put a 0 in the first 10 cells of each. Obviously you can change any of those numbers to do what you want.
Note/Disclaimer: I wrote this on my phone, so if I missed a brace or semicolon, just comment and I’ll add it. The logic is there, though.

Related

Difference between Objects of class and objects-array

Its part of codes.In the first part of code i wrote objects of class.This is fine i havent problem.My problem is on the second part of code
Paper[] pin = new Paper[N]; //N are given by keyboard .
for (int i=0; i < N, i++) //until the lenght N
{
pin[i] = new Paper();
}
pin[0].setpencil(3); // the number 3 i random chose it from my mind,i have done get and set methods
pin[0].getpencil(3);
i want to do it not for class and this is the second part of code down.If i want to create objects not using class this is right way?
int[] pin = new int[N];
for (int i=0; i < N, i++)
{
pin[i] = new int();
}
pin[0].setpencil(3);
pin[0].getpencil(3);
If you want to use an array of integers, just use int[N].
int[] pin = new int[N];
That's it. Java initializes primitives for you to 0 (zero) or false for boolean. You do not need a for loop to set the contents of the array, unless you want some value other than zero.
For example, to initialize all values of your array to 42:
int[] pin = new int[N];
for (int i=0; i < N, i++)
{
pin[i] = 42;
}
To read and write this array, you cannot use methods. Just treat the array deference like any other variable.
pin[0] = 3; // pin[0].setpencil(3);
System.out.println( pin[0] ); // pin[0].getpencil(3); prints "3"
However, classes must work differently (or at least they do in Java). If you have an object array instead of primitives:
Class Paper {
void getpencil(int n) {}
void setpencil(int n) {}
}
and an array
Paper[] myPaper = new Paper[N];
You must access this through methods; you cannot use the form above which is only for primitives.
myPaper[0].setpencil(3);
myPaper[0].getpencil(3);

Adding integers to an int array

I am trying to add integers into an int array, but Eclipse says:
cannot invoke add(int) on the array type int[]
Which is completely illogical to me. I also tried addElement() and addInt(), however they don't work either.
public static void main(String[] args) {
int[] num = new int[args.length];
for (String s : args){
int neki = Integer.parseInt(s);
num.add(neki);
}
To add an element to an array you need to use the format:
array[index] = element;
Where array is the array you declared, index is the position where the element will be stored, and element is the item you want to store in the array.
In your code, you'd want to do something like this:
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++) {
int neki = Integer.parseInt(args[i]);
num[i] = neki;
}
The add() method is available for Collections like List and Set. You could use it if you were using an ArrayList (see the documentation), for example:
List<Integer> num = new ArrayList<>();
for (String s : args) {
int neki = Integer.parseInt(s);
num.add(neki);
}
An array doesn't have an add method. You assign a value to an element of the array with num[i]=value;.
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i=0; i < num.length; i++){
int neki = Integer.parseInt(args[i]);
num[i]=neki;
}
}
An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.
int[] num = new int[5];
This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.
num[0] = 1;
num[1] = 2;
The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:
[1,2,0,0,0]
As you can see you set values in it, you don't add them to the end.
If you want to be able to create a list of numbers which you add to, you should use ArrayList.
You cannot use the add method on an array in Java.
To add things to the array do it like this
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++){
int neki = Integer.parseInt(s);
num[i] = neki;
}
If you really want to use an add() method, then consider using an ArrayList<Integer> instead. This has several advantages - for instance it isn't restricted to a maximum size set upon creation. You can keep adding elements indefinitely. However it isn't quite as fast as an array, so if you really want performance stick with the array. Also it requires you to use Integer object instead of primitive int types, which can cause problems.
ArrayList Example
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<Integer>();
for (String s : args){
Integer neki = new Integer(Integer.parseInt(s));
num.add(s);
}
Arrays are different than ArrayLists, on which you could call add. You'll need an index first. Declare i before the for loop. Then you can use an array access expression to assign the element to the array.
num[i] = s;
i++;
you have an array of int which is a primitive type, primitive type doesn't have the method add. You should look for Collections.
org.apache.commons.lang.ArrayUtils can do this
num = (int []) ArrayUtils.add(num, 12); // builds new array with 12 appended

Creating a custom sort for an array of integers?

Right, so I have a 2 part sorting algorithm. It's all based on an array of 14 random integers. For example:
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
Now, the first thing I'm trying to figure out how to do is to count how many a certain number exists in the original array. So, we know that 1 exists once, and 2 exists four times in the original array. But as easy as it is to visually see this, what if we don't have access to the original array. So I need to craft a method that will count how many of each number 1-9 exists and put this in a new array called count. So that index 0 in count would represent the integer 1 and would have a value of 1. Index 1 will represent the integer 2 and have a value of 4. And so on and so forth. Here is what I've got so far but I'm stuck. Sorting is pretty challenging for me.
public static void main(String[] args)
{
// int[] countFinal = {1,4,1,2,1,0,1,2,2}; // The number of times a number 1-9 appears in a[].
// int[] sortedFinal = {1,2,2,2,2,3,4,4,5,7,8,8,9,9}; // What we need as a final product.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//int[] count = {};
int[] sorted = {};
countHowMany(a, 1);
countHowMany(a, 2);
countHowMany(a, 3);
countHowMany(a, 4);
countHowMany(a, 5);
countHowMany(a, 6);
countHowMany(a, 7);
countHowMany(a, 8);
countHowMany(a, 9);
}
public static int countHowMany(int[] array, int value)
{
// Gathering a count for how many times a number 1-9 exists and adding it to count[];
int howManyCount = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] == value)
{
howManyCount++;
}
}
System.out.println(howManyCount);
count = new int[9];
count[howManyCount];
System.out.println(Arrays.toString(count); // Testing the input
return howManyCount;
}
It appears to count the number of times an item in the array exists properly. Now I just gotta figure out how I can add that value into a new array count[] and do it for each countHowMany(). This is the part I'm stuck on.
Once I have figured out count[] I can use it to create sorted[]. Now what sorted is supposed to do is take the data from the original array and count[] and create a new array that sorts it in ascending order and allows duplicates. So, since 1 occurs once and 2 occurs four times, the new array would be sorted[] = {1, 2, 2, 2, 2, ...}
It's a relatively small program and a small amount of integers, so it's ok that I create array's as necessary. The key being that I'm limited to using arrays and cannot use say ArrayLists for this.
You don't need to count each value individually. You can just iterate through the entire array and increment your counters for each element as you encounter it.
int counts = new int[20]; // Choose a value that's bigger than anything in your array.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
for (int value : a) {
counts[value]++;
}
If you don't know what the largest value in your array is likely to be, you're better to use either a Map to store the counts, or some kind of List that you increase the size of as needed.
You're better off just going through the array once and incrementing a counter for each value that might appear:
int counts[] = new int[10];
for (int n: array)
counts[n]++;
That's enough to put the count for each n in counts[n]. You can then read the values out of your count[] array.
You might not have come across this syntax for a for loop over an array, by the way. It's equivalent to
int counts[] = new int[10];
for (int i=0; i<array.length; i++) {
int n = array[i];
counts[n]++;
}
but it's less verbose.
Your method may as well be void, since you're not doing anything with the returned values of your countHowMany function. This will accomplish what you want:
public static void main(String[] args)
{
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//count the instances of each number in the array
int[] count = new int[9];
for(int i = 0; i < count.length; i++)
count[i] = countHowMany(a, i+1);
//put the values in the sorted array
int[] sorted = new int[a.length];
int position = 0; // stores the place in the array to put the new digit
for(int digit = 0; digit < 9; digit++)
{
for(int inst = 0; inst < count[digit]; inst++)
{
sorted[position] = digit + 1;
position++;
}
}
System.out.println(Arrays.toString(sorted));
}
The issue with your code is that you were trying to create the count array in each call of the countHowMany method, but this array is destroyed once the method finishes. The method calls should just return the counts, and then those returns should be put into the count array from outside the method. Note, however, that there are other ways to count the number of instances of each value, as noted by other answers.

Appending to double Array method

So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.

Sqrt, and Math in Arrays

I'm having difficulty understand how to write this array. I need it to out-print 10x5 (50 elements total), and have the first 25 elements equal to the sqrt of the index that it is in, and the last 25 to equal 3 * the index. Yes, this is homework but I'm not asking for you to do it for me, I just need help! I'm getting errors when using Math saying that I cant use double and the double array together. Here is what I have so far:
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double[10][5];
double[] sum, sum2;
for (int count=0; count<=25;count++) {
alpha[count]= Math.sqrt(count);
}
for (int count=26; count<=50;count++) {
alpha[count]= count *3;
}
for (int count=0; count<=50;count++) {
System.out.print(alpha[count]);
}
}
}
Because alpha is a multidimensional array, you can't refer to its elements like a normal array.
int myarray[][] = new int[2][2];
In the above example, the array myarray is multidimensional. If I wanted to access the second element in the first array, I would access it like this:
int myint = myarray[0][1];
You are trying to access a multidimensional array by using the access for a normal array. Change
alpha[count]
to
alpha[0][count]
or similar.
Read here for more information on multidimensional arrays.
you defined alpha as a 2D array with lets say 10 items in the first dimension and 5 in the second, and 5x10 is 50 elements.
When using your array to assign values to these elements, u must call upon the array using 2 indices, one for each dimension:
alpha[i][j] = /*double value*/; //with 0<=i<=9 and 0<=j<=4
So the first 25 elements going from left to right in dimension order is going to be:
[0to9][0] and [0to9][1] and [0to4][2]
the next 25 will be
[4to9][2] and [0to9][3] and [0to9][4]
from then on i cannot give you the answers to your homework, but the loops should look like this:
int j;
for(int i = 0; i<25; i++)
{
j=i/10; //integer division will return 0 for i<10, 1 for 10<i<20, etc..
alpha[i%10][j] = Math.sqrt(i);
}
and you can figure out the rest
The 10x5 appears to be an output constraint, not a design constraint.
You are using Java, so use Java constructs, not C-language constructs;
specifically store the values in a List not an array.
Here are some hints:
List<Integer> valuesList = new ArrayList<Integer>();
for (int index = 0; index < 25; ++index)
Integer currentValue = Math.sqrt(index);
valuesList.add(currentValue);
for (int index = 25; index < 50; ++index)
Integer currentValue = index * 3;
valuesList.add(currentValue)
int count = 1;
for (Integer current : valuesList)
if ((count % 5) == 0) // write a newline.
System.out.print(current);
++count

Categories