How to create a vector without determining its size in java?

9

I have a TesteAplicacao class that is to test and a Teste class with attributes and methods.

When creating a vector in Java:

Teste[] t = new Teste[10];// veja que teve definir um tamanho 

Would you like to create vector without equal size set in C?

    
asked by anonymous 03.03.2016 / 17:24

5 answers

11

Simple, use a ArrayList . The array of Java can only be fixed length. There are other options, but most of the time this is the best.

I'd use something like this:

ArrayList<Teste> t = new ArrayList<>(10);
t.add(new Teste());
t.get(0).nome = nome1;
System.out.println(t.get(0).nome);
t.add(new Teste());
t.get(1).nome = nome1;

I started the list capacity with 10, but could start with any size. This does not mean that you will already have 10 elements on the list, only that it has already started that size. 10 is the default size, so in that specific case you would not even need to put it. It's good to use a size that you think you'll need to avoid relocation.

Just remembering that this allows you to have a collection of data that can vary in size at run time without major concerns. Ma Java allows you to easily define a normal array with no given size at compile time, equal to C. What you can not do is have its size changed after it is created, equal to C.

Actually there is no data in computing that is not determined at any time, what you can do is to determine it as soon as possible (its creation) and to be able to resize it (usually requires reallocation in most cases ).

ArrayList is just a structure that manages reallocations for you.

    
03.03.2016 / 17:28
6

If you need a list, with no set size, use Java.util.ArrayList or LinkedList .

In Java it is not possible to create an array with flexible size.

    
03.03.2016 / 17:27
4

Not exactly, the size of arrays should be set at some point and you can not change it after that. An alternative would be to just declare your Teste[] t; array and set the size at some later point with something like t = new Teste[size] , yet you're still stuck needing to eventually determine the size. Another, more flexible, would be to use implementations of the List interface, for example ArrayList which is essentially a class that abstracts a vector and can have size variable.

Example usage:

// instancia o objeto ArrayList
ArrayList<Teste> list = new ArrayList<Teste>();
// adiciona um item
list.add(new Teste());
// adiciona outro item
list.add(new Teste());
// etc, veja a doc de arraylist para os outros métodos.
    
03.03.2016 / 17:37
4

Can not create vector with variable length. What you can do is to dynamically vary the size of the vector that is created, as in C99.

Creating array by varying size

Example:

Test[] create(int size) {
    return new Test[size];
}

The above code creates a new vector of class Test with the size passed by parameter. Soon you can create this vector of the size you need:

    Test[] array1 = create(10);
    Test[] array2 = create(20);
    Test[] array3 = create(lerEntradaDoUsuario());

Cloning the array with a new size

Although Java does not support resizing arrays, because of efficiency in memory usage, the basic solution if you need to increase it is to make a copy of the current array in a new array of the desired size.

This is very simple using the Arrays class of Java:

//cria o array inicial
Test[] array = new Test[10];

//coloca um elemento na primeira posição
array[0] = new Test();
array[0].nome = "Eu";

//imprime o tamanho atual do array
System.out.println(array.length);

//clona o array atual em um novo array com 20 posições
//atribuindo na mesma variável
array = Arrays.copyOf(array, 20);

//imprime o tamanho do novo array
System.out.println(array.length);

//imprime o valor do elemento para provar que ele ainda está lá
System.out.println(array[0].nome);

ArrayList

The above example is interesting, but it's easier to use an implementation that already takes care of that.

As already exemplified in other answers, ArrayList can be used as a variable-length data structure.

Under the wipes, it does exactly what I did in the example above, that is, it has an inner vector that is resized when you add more elements than it supports at a given time.

    
04.03.2016 / 00:20
0

A vector needs a fixed size, if you need a dynamic vector you can instantiate an arrayList and use the toArray function to transform the array into vector.   List<Object> lista = new ArrayList<>(); lista.add("objeto1"); lista.add("objeto2"); Object[] vetor = lista.toArray();

    
25.03.2016 / 01:22