开发者

Question about using ArrayList in Java?

I really do not know if the title is appropriate or not.

I have 2 options: OPTION 1:

Class A {
   ArrayList<B> BList = new ArrayList<B>();

   public B[] getBList() {
       return (B[])BList.toArray();
   }
}

Class Facade {
   public B[] getAllB(){
       A a = new A();
     开发者_Go百科  return a.getBList();
   }
}

OPTION 2:

Class A {
   ArrayList<B> BList = new ArrayList<B>();

   public ArrayList getBList() {
       return BList;
   }
}

Class Facade {
   public B[] getAllB(){
       A a = new A();
       ArrayList BList = a.getBList();
       return (B[])BList.toArray();
   }
}

Which option should i use ?


Use collection classes, unless you have a specific reason to use arrays. So, I'd choose option 2.

There are a number of other comments that can be made about your code.

First, It's better to program to an interface, not an implementation - make the member variable BList in class A a List<B> instead of an ArrayList<B>. Also, member variables should be private (unless there's a very good reason for them not to be private). Third, use generics whenever possible - why does your method getBList() return a raw ArrayList? The de-facto naming standard for variables in Java is camel case, starting with a lower-case letter. So don't call the member variable BList, but bList (or some other, better name).

class A {
    private List<B> bList = new ArrayList<B>();

    public List<B> getBList() {
        return bList;
    }
}

Is it really necessary for class Facade to return a B[]?

Another point to consider is to make your class A immutable, because unexpected things might happen if you'd get the list from an A object, and then add or remove elements from the list (the list inside your A object will also be changed and that can be confusing). You'd have to return a read-only view of the list in your getBList() method:

public List<B> getBList() {
    return Collections.unmodifiableList(bList);
}


I don't have a strong preference either way. However, I notice you're using an array to return the list's contents, perhaps in an attempt to make it immutable. I recommend, instead, using Collections.unmodifiableList.


I think the only difference is whether Class A is part of the public interface of your component.

If it's not (e.g. only the Facade counts to the public interface), then it does not matter.

If Class A is part of the public interface, i'd go with Option 1.


Unless you really need too, where the native formt of something is bytes[] for something like images, one should always return Collection types in an API for a many of something rather than an array. In your case wrap the original Collection using Collections.unmodifiableXXX( ...).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜