List processing inside a class

Say I have a class A that has a list of related elements (the type of elements doesn't matter):

public class A {
  private List<String> list;

  public List<String> getList() {
    return list;
  }

  public void addElement(String element) {
    list.add(element);
  }
}

Now I want to access this list from another Client class. I need to add a new item. A more philosophical question is how best to do this from a design point of view.

public class Client {
  private A a = new A();

  public void method1() {
    a.getList().add("");
  }

  public void method2() {
    a.addElement("");
  }    
}

If anyone can point out any advantage of any of these methods, it would be very appreciated. Thank.

+3
source share
8 answers

getList() . A List, clear() , ---. Iterator List Collections.unmodifiableList().

, 2, addElement() ; addElement() , . clear() .

+9

, method2 OOP-. ( method2 addAll ..)

API:

, - , , ...


, , , remove .., , , add, method1 .

API:

+5

(.. getList()), , addElement. , , .

+1

public void method2() {
    a.addElement("");  
} 

A. , , A, A , .

, , , , , A, !: P

A .

+1

A. getList(), .

B a.addElement(). , B A, A , B .

OO Encapsulation. , .

method2(). a.getList() B, OO.

+1

. , .
, A ... .

0

A. List , .

0

method2 , . , .

0

All Articles