creating array without declaring the size - java

后端 未结 6 1136
面向向阳花
面向向阳花 2020-12-13 16:29

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 w

相关标签:
6条回答
  • 2020-12-13 16:52

    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);
    
    0 讨论(0)
  • 2020-12-13 16:59

    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.

    0 讨论(0)
  • 2020-12-13 17:03

    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).

    0 讨论(0)
  • 2020-12-13 17:04

    How about this

        private Object element[] = new Object[] {};
    
    0 讨论(0)
  • 2020-12-13 17:10

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

    0 讨论(0)
  • 2020-12-13 17:18

    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.

    0 讨论(0)
提交回复
热议问题