creating array without declaring the size - java - java

i've digging around about the same issue but i couldn't find the same as i had
i want to create an array without declaring the size because i don't know how it will be !
to clear the issue i'd like to give you the code that i'm looking up for
public class t
{
private int x[];
private int counter=0;
public void add(int num)
{
this.x[this.counter] = num;
this.counter++;
}
}
as you see the user could use the add function to add element to the array 10000 times or only once so it's unknown size

Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.
Example:
List<Float> unindexedVectors = new ArrayList<Float>();
unindexedVectors.add(2.22f);
unindexedVectors.get(2);

You might be looking for a List? Either LinkedList or ArrayList are good classes to take a look at. You can then call toArray() to get the list as an array.

As others have said, use ArrayList. Here's how:
public class t
{
private List<Integer> x = new ArrayList<Integer>();
public void add(int num)
{
this.x.add(num);
}
}
As you can see, your add method just calls the ArrayList's add method. This is only useful if your variable is private (which it is).

Once the array size is fixed while running the program ,it's size can't be changed further.
So better go for ArrayList while dealing with dynamic arrays.

How about this
private Object element[] = new Object[] {};

I think what you really want is an ArrayList or Vector. Arrays in Java are not like those in Javascript.

Related

how can i initialize my array when i cant initialize as null?

i have an array of strings which i want to convert to int, pretty simple and straightforward here is the code :
public static void main(String[] args) {
String myarray[]=readfile("[pathtothefile]");
int mynums[] = new int[myarray.length];
for (int i=0;i<myarray.length;i++){
mynums[i]=Integer.parseInt(myarray[i]);
}
System.out.print(Arrays.toString(mynums));
}
But the Problem here is, if i initialize "mynums" like this: mynums[]=null; i get NullPointerException on the following line:
"mynums[i]=Integer.parseInt(myarray[i]);"
what i have to do to solve it is
int mynums[] = new int[myarray.length];
here someone explained why it happens but i dont know how to initialize now! i mean sometimes i dont know how big my array can get and i just want to initialize it. is it even possible?
In Java everything is a pointer behind the scenes. So when you do mynums[]=null, you are pointing to a null. So what is null[i]? That is where your NPE comes from. Alternatively when you point it to an array, then you are actually accessing the i'th element of the array.
You have to first initialize the array because it allocates memory depending on the array size. When you want to add for example an integer to an array it writes the int into previously allocated memory.
The memory size won't grow bigger as you add more items.( Unless you use Lists or Hashmaps, ... but it's not true for generic arrays)
If you don't know how big your array will be, consider using SparseIntArray. which is like Lists and will grow bigger as you add items.
Briefly, in java an array is an object, thus you need to treat it like an object and initialize it prior to doing anything with it.
Here's an idea. When you're initializing something as null, you're simply declaring that it exists. For example ... if I told you that there is a dog, but I told you nothing about it ... I didn't tell you where it was, how tall it was, how old, male/female, etc ... I told you none of its properties or how to access it, and all I told you was that there IS a dog (whose name is Array, for sake of argument), then that would be all you know. There's a dog whose name is Array and that is it.
Typically, arrays are used when the size is already known and generally the data is meant to be immutable. For data that are meant to be changed, you should use things like ArrayList. These are intended to be changed at will; you can add/remove elements at a whim. For more information about ArrayList, read up on the links posted above.
Now, as for your code:
public static void main(String[] args) {
ArrayList<int> myInts = new ArrayList<int>();
// define a new null arraylist of integers.
// I'm going to assume that readfile() is a way for you get the file
// into myarray. I'm not quite sure why you would need the [], but I'll
// leave it.
String myarray[] = readfile("[pathtothefile]");
for (int i = 0; i < myarray.length; i++) {
//adds the value you've specifed as an integer to the arraylist.
myInts.add(Integer.parseInt(myarray[i]));
}
for (int i = 0; i < myInts.size(); i++) {
//print the integers
System.out.print(Integer.toString(myInts.get(i)));
}
}
What if you don't use an array but an ArrayList? It grows dynamically as you add elements.

Java Constructor to take an array?

I have created a default constructor which creates an empty "hand".
public Hand() {
hand = new ArrayList();
}
Whats the most efficient way to have a second constructor take an Array of cards, then add them a hand?
I would have one constructor to do both.
public Hand(Card... cards) {
hand = Arrays.asList(cards);
}
Or an ArrayList copy as Rohit Jain suggests.
You can do it like this: -
public Hand(String[] hands) {
hand = new ArrayList<String>(Arrays.asList(hands));
}
Or, you can iterate over your string array, and add individual elements to your ArrayList.
public Hand(String[] hands) {
hand = new ArrayList<String>();
for (String elem: hands)
hand.add(elem);
}
P.S: - Always declare a Generic Type List.
There's another option, Collections.addAll:
public Hand(Card[] cards) {
hand = new ArrayList<Card>();
Collections.addAll(hand, cards);
}
According to the documentation:
Adds all of the specified elements to the specified collection.
Elements to be added may be specified individually or as an array. The
behavior of this convenience method is identical to that of
c.addAll(Arrays.asList(elements)), but this method is likely to run
significantly faster under most implementations.

ArrayList with arrays in it. How to get them out. code is posted

Little problem.. i want to add some arrays to my arraylist and later get acces to print them out.
Her is my code..
import java.util.*;
class List
{
private ArrayList<int[]> X;
private int[] list;
public X()
{
X = new ArrayList<int[]>();
}
public void addList(int[] list)
{
this.X.add(list);
}
public void showList(int listNumber)
{
System.out.println(X.get(listNumber));
}
Problem is im not getting my list out, but the int code something ... dunno what it really is..
Your problem is in line System.out.println(X.get(listNumber));. Every java object has method toString(). Arrays also have such method but its implementation shows the array reference. To print the array content either iterate over it and print element-by-element or use utility like Arrays.toString():
System.out.println(java.util.Arrays.toString(X.get(listNumber)));
This is because arrays toString() which is called here prints out array reference, not it's contents.
Use instead custom output:
for (int i : X.get(listNumber))
System.out.print(i + " ");
Or, as AlexR proposed, better use provided JDK method Arrays.toString();
By the way, you don't need to prefix this. everywhere in your class' code.
Iterate over all integer arrays in X and in each item (array) print it elements.
This function will do the job for you.
public void printAll(){
for(int [] item:X){
for(int num :item){
System.out.print(num);
}
System.out.println();
}
}
You need to use the Arrays class from java.util.Arrays:
System.out.println(Arrays.toString(X.get(listNumber)));
Just printing out an array prints out its memory location, so to get the actual values, you have to get each element individually, which is what Arrays.toString() does for you.
You are trying to get the array. If you want to display the results of the array you need to do loop through each value in X.get(listNumber) and display the results of the loop.

in java, is it possble to name an array from a string?

I am a beginner with java, and I was wondering is if is possible to name and create an array from the value of a string.
Here is what I have:
public static void array(){
createArray(array1, 100, 100);
}
public static void createArray(String name, int r, int c) {
int[][] name = new int[r][c];
}
I hope that explains itself. Thanks
EDIT: The code above does not work. I just want to know if it is possible to do what is above
EDIT2: As a beginner with java, I am just watching tutorials, and creating programs with what I learned to make sure I understand what is being taught. I first created a program which creates s multidimensional arrays. It then calls a method which assigned values to the array, (row+1)*(column+1). This makes a table much like a multiplication table. Then it displays the table to the screen.
After I created that program, I wanted to be able to create arrays much like I assigned the values to it. So i asked this question...
Here is my code:
public static void array(){
int[][] array1 = new int[100][100];
int[][] array2 = new int[20][20];
setArrayValue(array1);
setArrayValue(array2);
drawArray(array1);
System.out.println();
drawArray(array2);
}
public static void setArrayValue(int x[][]){
for(int row = 0; row<x.length; row++){
for(int column=0; column<x[row].length; column++){
x[row][column]= (column+1)*(row+1);
}
}
}
public static void drawArray(int x[][]){
for(int row=0; row<x.length; row++) {
for(int column=0; column<x[row].length;column++){
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
}
Your concept doesn't make sense.
You might want to use a Map<String, int[][]>, which will map names to arrays.
What you are trying to do is not possible in Java. In the createArray method, name is of type String and cannot be redeclared as an int array.
Perhaps you are interested in a Map that uses String objects as keys? The values could be int arrays (or any other object).
No, you can't do that.
Variable names are not variable in Java.
Furthermore, local variables even lose their names when the code is compiled. Variable names are just a help for the programmer to distinguish between variables.
Nop can't be done. Variable names need to be known before hand.
No, it is not possible. You might be able to accomplish your task with a TreeMap or another Map implementation instead.
Instead of saying
name = something;
You would say
map.put(name, something);
Instead of
name[0] + 7
You'd say
map.get(name)[0] + 7
As stated by others - this cannot be done. That is because Java compiler needs to know exact name of a variable at the compile time. This is mandatory, since otherwise Java compiler wouldn't know which variable you are addressing, so it couldn't perform, for instance, type-safety checks.
However, if you just wish to stamp your variable with some unique ID, I guess the solution is closest to what has been stated by SLaks. Simply use Map, and You should be good. Example below.
Map<String, int[][]> myMap = new HashMap<String, int[][]>();
myMap.put("someUniqueName", new int[][] {{0,0}, {1,1}});
and later on:
int[][] array = myMap.get("someUniqueName");
Hope that helps achieve what You want.
Strictly: almost ;-) You can add a dynamic field in a class, which could be an array, using AOP. But...
It's difficult.
This solution is too complicated in most cases. You could probably solve your real problem in a much easier way.
Some advice: start with the beginning... and try using List (interface) / ArrayList as much as possible unless you have some pretty good reason to use an array.

Java - ArrayList<Integer> as Parameter...?

I would like to know how to create a method which takes an ArrayList of Integers (ArrayList) as a parameter and then display the contents of the ArrayList?
I have some code which generates some random numbers and populates the ArrayList with the results, however I keep having errors flag up in eclipse when attempting to create this particular method.
Here is what I have so far:
public void showArray(ArrayList<Integer> array){
return;
}
I know that it is very basic, but I am unsure exactly how to approach it - could it be something like the following?
public void showArray(ArrayList<Integer> array){
Arrays.toString(array);
}
Any assistance would be greatly appreciated.
Thank you.
I'm assuming this is a learning exercise. I'll give you a few hints:
Your method is named showArray, but an ArrayList<T> is of type List<T>, and is not an array. More specifically it is a list that is implemented by internally using an array. Either change the parameter to be an array or else fix the name of the method.
Use an interface if possible instead of passing a concrete class to make your method more reusable.
Minor point: It may be better to have your method return a String, and display the result outside the method.
Try something like this:
public void printList(List<Integer> array) {
String toPrint = ...;
System.out.println(toPrint);
}
You can use a loop and a StringBuilder to construct the toPrint string.
Is there any reason why System.out.println( array ); wouldn't work for you?
Output will be like:
[1, 2, 3]
If you are looking to print the array items, try
public void showArray(ArrayList<Integer> array){
for(int arrayItem : array)
{
System.out.println(arrayItem);
}
}
This sounds like someone wants us to do their homework. You don't have to return anything if you are just displaying it, and if the method has a void return type. I don't know exactly what you want but is it something along the lines of System.out.println(array.elementAt(index))? then you would need a loop.

Categories