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

Asked

Viewed 12,645 times

10

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

When creating a vector in Java:

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

It would be possible to create vector with no defined size equal in C?

  • 1

    Which vector in C does not have the set size?

  • 2

    @utluiz he’s probably talking about array set in runtime available on C99. Or you may be talking about pointers accessed as if they were arrays, less likely. Anyway, of course there is always a set size. https://en.wikipedia.org/wiki/Variable-length_array What in Java can be done directly.

5 answers

13


Simple, use a ArrayList. The array Java can only have fixed size. There are other options, but almost always this is the best.

I’d wear it more or less 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 put in the Github for future reference.

I started the list capacity with 10, but could start with any size. This does not mean that it will already have 10 items on the list, only that it has already reserved this size in memory. 10 is the default size in the current implementation, so in this specific case you wouldn’t even have to put it in. It’s good to use a size 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 runtime without major worries, but Java allows you to easily define a array normal with no specified build time size, equal to C. What you cannot have is your size changed after created, equal to C.

Actually there is no data in computation that does not have its size determined at some point, what you can do is determine it as late as possible (its creation) and be able to change the size (usually requires relocation in most cases).

The ArrayList is just a structure that manages relocations for you.

  • In the arrayList how do I use so t[0].valor = i; t[0].nome = nome1; t[1].valor = i; t[1].nome = nome1;..........

  • @Bigown Yes, the initial capacity is 10 -> doc

6

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

Java cannot create a flexible-sized array.

  • In the arrayList how do I use so t[0].valor = i; t[0].nome = nome1; t[1].valor = i; t[1].nome = nome1;..........

  • with this you want to add a new value (add) or change an existing value (set)?

4

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

Example of use:

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

4

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

Creating array varying in size

Example:

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

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

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

Cloning the array with new size

Although Java does not support resizing arrays, for reasons of memory usage efficiency, 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 class Arrays 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 previous example is interesting, but it is easier to use an implementation that already takes care of it properly.

As already exemplified in other answers, the ArrayList can be used as a data structure of variable size.

Underneath the cloths, it does exactly what I did in the example above, that is, it has an internal vector that is resized when you add more elements than it supports at any given time.

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 a vector. List<Object> lista = new ArrayList<>(); lista.add("objeto1"); lista.add("objeto2"); Object[] vetor = lista.toArray();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.