如何使用增强的for循环打印出ArrayList的值?

时间:2016-11-01 19:39:06

标签: java arraylist

我一直试图找出一种方法来打印出一个增强的for循环语句的值现在已经有一段时间了,似乎无法弄清楚如何去做。我理解增强的for循环的基本概念,但我似乎无法弄清楚如何在我的场景中使用它。

以下是代码:

 import java.util.ArrayList;

public class userGroup {

    ArrayList<User> userGroup = new ArrayList<>();
    User user0;

    public void addSampleData() {

    userGroup.add(user0);

    }

    public void printusername(){

       for (User x: userGroup)
           System.out.println(x);
    }
}

如何在打印出user0及其值的printusername方法中实现for循环语句?我知道这可能是因为在创建ArrayList时某处出现了错误,但我无法找出错误的位置。我和任何可能有同样问题的人都会非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:0)

我认为你已经足够接近答案了,但让我们更简单一点。让我们展示一个类似的案例,只用一种方法来获得一些点。

    public void printUsername() {  //note the case.  this is by convention in Java.

        //The left side is using the Collection interface, not an ArrayList.  
        //This is the weakest interface that we can use.   
        //We are also using generics to show that we have a Collection of User objects.

        //Lastly, we include the number one to show that we are 
        //creating an ArrayList with an initial capacity of 1.  We are just
        //adding one object.

        Collection<User> userGroup = new ArrayList<>(1); 

        //We create an object by using the "new" keyword
        User user0 = new User(); 

        //and now we add it to the Collection we created earlier
        userGroup.add(user0); 

        //now iterate through the loop
        for (User user: userGroup) {  //note the use of braces for clarity
            //this will call toString on the User object
            //if you don't implement toString(), 
            //you'll get a rather cryptic address (technically, a hashcode of the object)

            //try to make your variable names mean something too.
            //it's much easier to track down issues later when your variable
            //names make sense.  And it's much easier for the next person
            //trying to make sense of your code.
            System.out.println(user);  
        }
    }

如果您使用的是Java 8或更高版本,则可以使用collect调用替换增强的for循环:

    userGroup.forEach(System.out::println);