简体   繁体   中英

How to get a specific element from an arraylist that has string and int values from another class

here is my problem.

I have a class A that has a string of names and int of numbers which is placed into an ArrayList of another class.

Task:- what i need to do is get the first name from index(0) from the arraylist and return it as a string.

public class A
  {  
  private String name;
  private int num;
  public A(String aName, int bNum)
  {
    name = aName;
    num = bNum;
  public String getName()
  {return name; }
  public int getNum()
  {return num;}
  }
  } 

//class b inserts elements of class a into arraylist
public class b
  {
  private ArrayList<A> myList;
  }
  public b()
  myList = new ArrayList<A>;

  public void addAll(A all)
  { myList.add(all);}

//get method required for issue above.

Check if the the your list has any item present or no. If present, retrieve the first element and get the name for it to return otherwise return null or empty string as desired.

    public String getFirstElementName(){
        String name = null;//or ""
        if(myList.size() >0){
           name = myList.get(0).getName);
        }
        return name;
    }

EDIT:

    public A getFirstElement(){
        A a = null;//or ""
        if(myList.size() >0){
           a= myList.get(0);
        }
        return a;
    }

Where you are calling this method, you may write as:

   A a = getFirstElement();
   String name = a.getName();
   int number= a.getNum();

Hope this helps.

List.get(int index) returns the element at position index .

May be what you are looking for is

A firstA = myList.get(0);
String name = firstA.getName();

Also, instead of declaring your list as

private ArrayList<A> myList;

you should declare it as

private List<A> myList;

Code against the interface wherever possible.

You need to override equals() and hashcode() in class A based on object equality requirements.

When you want to do lookup create object for A and set values and do lookup with this object.

Example:

A tempObj = new A("name", 5);

In Class B

myList.get(tempObj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM