How do I create an Arraylist of objects with each position containing a new object?

Asked

Viewed 412 times

0

public class Produto {

       String marca;
       int quant;

       Produto prod = new Produto();
       ArrayList <Produto> lista_de_produtos = new ArrayList<>(); 
       lista_de_produtos.add(new Produto());

       //É dessa forma?

}
  • Are you having a problem? That’s what does what you ask. Sure, there are a lot of problems in doing it so simply, but then it depends on the context.

  • 1

    What is your question? Give an example of what you want to achieve.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

3 answers

4

You should not do so. The code compiles and executes, but this form is considered wrong.

The class calls Produto, So what do you expect to have in it? A product, right? Why do you find a list of products in that object? Even worse, there will be a different list in each product. This doesn’t make any sense. If at least the list were static, and then belonging to the class and not to the object, it would even have a partial sense, but it would still be conceptually wrong because it should be in another class of stock control and not the product.

Conceptually, there should be another class that handles the list of products. Nor will I get into the merits of the application to be able to run in a concurrent environment and this would be a problem, I will consider it a non-existent possibility.

Another problem of this class is that the constructor does not accept parameters, i.e., it works as a builder in fact. This is another conceptual error. I also didn’t talk about encapsulation and abstraction, because this is even more confusing and there are controversies, and I’m not even saying that I should.

1

Following your question and the comments between you and the @Maniero, I will leave my answer below, but I make it clear that you must pay attention to the following @Maniero:

  • to) Read the answer carefully.
  • b) Carefully read the comments in your answer to your own question.

Well, come on... how come you didn’t detail your question, like for example: "What you really want?", "What are the business rules?" among others, I will leave below the explanations of concepts and how they should be used in the correct way.

What is an Arraylist?

The Class ArrayList is a scalable matrix , which can be found in the package java.util. The difference between a internal matrix and a ArrayList in Java is the following:

  • The size of an array cannot be modified (if you want to add or remove elements from/to an array, you will need to create a new one).

  • While in a ArrayList elements can be added and removed from one whenever you want.

  • The syntax between a ArrayList and a internal matrix is also a little different

How to create an Arraylist?

You must import the library (package) from it and after this instantiate the object, inserting its type and its name, for example:

// importa a biblioteca (pacote) do ArrayList
import java.util.ArrayList;

// Cria um Objeto de ArrayList chamado cars e do tipo de armazenamento String
ArrayList<String> cars = new ArrayList<String>(); 

// Cria um Objeto de ArrayList chamado cars e do tipo de armazenamento Car
Car carObj = new Car();
ArrayList<Car> cars = new ArrayList<Car>();

How to store data in an Arraylist?

ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");

How to access the index of an Arraylist?

cars.get(0);
cars.get(1);
cars.get(2);

Now giving example using your question, using a simple situation and only for knowledge gains, you should do the following:

  • Creating a Class for Products
  • Creating a Class for Product Lists

Listaproduct.class

import java.util.ArrayList;

public class ListaProduto {
    private ArrayList<Produto> arrProd;
    
    public ListaProduto() {
        this.arrProd = new ArrayList<Produto>();
    }
    
    public void addProd(Produto prod) {
        this.arrProd.add(prod);
    }
    
    public void getAllProd() {
        for(int i = 0; i < this.arrProd.size(); i++) {
            System.out.println("\nREF DO OBJ: " + this.arrProd.get(i) + " -- "  + "MARCA: " + this.arrProd.get(i).getMarca() + " -- QUANTIDADE: " + this.arrProd.get(i).getQuantidade());
        }
    }

    
}

Java product.

public class Produto {
    private String marca;
    private int quantidade;
    
    public Produto(String marca, int quantidade) {
        this.marca = marca;
        this.quantidade = quantidade;
    }
    
    public String getMarca() {
        return this.marca;
    }
    
    public int getQuantidade() {
        return this.quantidade;
    }

}

Main java.

public class Main {
    public static void main(String[] args) {
        ListaProduto lp = new ListaProduto();
        
        for(int i = 0; i < 4; i++) {
            lp.addProd(new Produto("PRODUTO " + i, i));
        }
        
        lp.getAllProd();
    }

}

OUTPUT:

REF DA CLASS: Produto@15db9742 -- MARCA: PRODUTO 0 -- QUANTIDADE: 0
REF DA CLASS: Produto@6d06d69c -- MARCA: PRODUTO 1 -- QUANTIDADE: 1
REF DA CLASS: Produto@7852e922 -- MARCA: PRODUTO 2 -- QUANTIDADE: 2
REF DA CLASS: Produto@4e25154f -- MARCA: PRODUTO 3 -- QUANTIDADE: 3

NOTE:

The above code was given for the purpose of gaining knowledge, there are several other ways and mainly best and best practices to do the same.

OFFICIAL SOURCE - W3SCHOOLS

0

That’s basically how it is. It’s important to remember the context of your application. More generally this is the code I used to validate.


import java.util.ArrayList;

public class Produto {

    public Produto(){

    }

    public static void main(String[] args) {

     String marca;
     int quant;

     Produto prod = new Produto();
     ArrayList<Produto> lista_de_produtos = new ArrayList<>(); 
     lista_de_produtos.add(new Produto());
     lista_de_produtos.add(new Produto());

    }

}

  • You say it’s like that, but you wrote a code that does something different, I don’t understand.

  • The code is creating an Arraylist and at each position has a new product. Maybe you are confusing some language concepts. What exactly do you want to do?

  • I don’t want to do anything, I’m saying your answer is contradictory, it says the question code is correct, but it says to do it differently. This I don’t understand, if his code is correct, why are you telling me to do it differently? What concepts of language do you think I’m confusing?

  • I answered more above that basically the way you did it is right and that I saw it through the code I put in the answer: Creating a class and running the code you did in a main method. Only that.

  • I didn’t do anything, I just gave an answer, you can read it. I’m sorry but all this talking doesn’t make sense. I’ve seen that we’ll be in circles.

  • @Iranneto I think what @Maniero wants to say is this: In your question your code does not make any sense, because in class Produto {} you are instantiating and creating new objects of it, in itself and adding the objects of the products in a ArrayList. Which makes no sense and breaks many concepts of the language, to do this you need to create another class which is a list of products and instill the product and the array inside.

  • @Maniero?

  • 1

    @THIAGODEBONIS didn’t even get to that point, just the fact that writing one code is right and then showing another one doesn’t make sense, if it’s right, it shouldn’t show another. Nor does it make much sense to do that, although depending on the context is not a big problem, in fact this code of the answer is more appropriate than that of the question (for an exercise), and nor is it because of the concept of language, it is because of semantics of the code as a whole, is a domain problem, in my answer I talk about this.

  • Is this code right in a context? I’m sorry but the "SOLID" that exists within me gave conflict, and gave me a bug...

  • @Ricardolucas yes, the one of a very basic exercise that is evaluating another aspect, the one of a software throw away and many others that do not require anything very correct to work.

Show 5 more comments

Browser other questions tagged

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