简体   繁体   中英

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();
       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 (eg 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( ...).

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