Pergunta

So this is my Code, I'm working on Ecplise:

main.java

public class Main {

public static void main(String[] args)
{

    Conjunto<Integer> ts1 = new Conjunto <Integer>();
    ts1.add(1);
    ts1.add(2);
    ts1.add(3);
    ts1.add(4);
    ts1.add(6);
    ts1.contieneA(8);
    System.out.println(ts1);

    Conjunto<Integer> ts2 = new Conjunto <Integer>();
    ts2.add(5);
    ts2.add(6);
    ts2.add(7);
    ts2.add(8);
    ts2.add(9);
    System.out.println(ts2);

    Conjunto<Integer> ts3 = new Conjunto <Integer>();
    ts3.add(4);
    ts3.add(7);
    ts3.add(9);
    ts3.add(10);
    System.out.println(ts3);


}
}

4.1 Works perfectly, but 4.2 is supposed to give me the size of the array by using .size(), however I'm not sure how to get the size of ts1 through a method

Conjunto.java

import java.util.ArrayList;

public class Conjunto<Categoria> {

private ArrayList <Categoria> data;

public Conjunto()
{
    data = new ArrayList<Categoria>();
}

public void add(Categoria elemento)
{
    int Maxuno = data.indexOf(elemento);
    if(Maxuno == -1)
    {
        data.add(elemento);
    }

}

public String toString(){
    return data.toString();
}

//4.1
public boolean contieneA(Categoria elemento)
{
    int cont = data.indexOf(elemento);
    if(cont == -1) 
    {
        System.out.println("false");
        return false;
    }
    else{
        System.out.println("true");
        return true;
    }
}

//4.2
public int thesize()
{
    return ts1.size();
}
Foi útil?

Solução

You need to change this code

public int thesize()
{
    return ts1.size();
}

To something like this, which will return the size of the ArrayList wrapped by the class.

public int thesize()
{
    return data.size();
}

You can't refer to a specific instance of a class inside the class. You can only do that when that specific instance (or a reference to it) exists.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top