有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

打印ArrayList时的java冗余结果

   import java.util.ArrayList;
   import java.util.List;

   public class Apple {
        private static String color;
        private static int weight;
        public Apple(String color, int weight){
            this.color = color;
            this.weight = weight;
        }
        public int getWeight(){
            return weight;
        }
        public String getColor(){
        return color;
        }
        public interface AppleFormatter{
            String accept(Apple a);
        }
        public static class AppleFancyFormatter implements AppleFormatter{
            public String accept(Apple apple){
                String characteristic = apple.getWeight() > 150 ? "heavy" :     "light";
                return "A " + characteristic + " " + apple.getColor() + "  apple";
            }
        }
        public static class AppleSimpleFormatter implements AppleFormatter{
            public String accept(Apple apple){
                return "An apple of " + apple.getWeight() + "g";
            }
        } 
        public static void prettyPrintApple(List<Apple> inventory,  AppleFormatter formatter){
            for(Apple apple: inventory){
                String output = formatter.accept(apple);
                System.out.println(output);
            }
        }
        public static void main(String[] args){
            List<Apple> arrayList = new ArrayList<>();
            Apple app1 = new Apple("green", 155);
            Apple app2 = new Apple("yellow", 160);
            Apple app3 = new Apple("red", 130);
            arrayList.add(app1);
            arrayList.add(app2);
            arrayList.add(app3);

            prettyPrintApple(arrayList, new AppleFancyFormatter());
            prettyPrintApple(arrayList, new AppleSimpleFormatter());

        }
    }

打印以下代码: 淡红色的苹果 淡红色的苹果 淡红色的苹果 一个130克的苹果 一个130克的苹果 一个130克的苹果

我注意到我的数组有一种趋势,即不正确地迭代,而是不断地打印我创建的最后一个对象。我不知道这是为什么。我错过了什么enter code here


共 (1) 个答案

  1. # 1 楼答案

    你的字段是静态的

     private static String color;
     private static int weight;
    

    所以所有的苹果都有相同的颜色和重量!删除静态关键字,一切正常