How do you put the class in the method?



  • There's a piece of java code.

    final List<Advertisement> advertisements = new ArrayList<>();
    new Object() {
        public void recurse(int i) {
            advertisements.add(storage.list().get(i));
            if (i + 1 < storage.list().size())
                recurse(i + 1);
        }
    }.recurse(0);
    

    It's supposed to copy the elements of the sheet from storage.list() in the advertisements in this way, but somehow the sheet code is empty, which might not be the case?



  • It's hard to tell me why you don't work. Maybe the problem is another code we don't see. However, one inaccuracy can be stated immediately - always implemented storage.list().get(0) without checking the list. This could lead to an exception.

    Looking at the idea, it's quite workable. Here's a slightly changed working code:

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

    class Test {
    public static void main(String [] args) {
    final List<String> list1 = new ArrayList<>();
    final List<String> list2 = new ArrayList<>();

        list1.add("String 1");
        list1.add("String 2");
        list1.add("String 3");
    
        new Object() {
            public void recurse(final int i) {
                if (i &lt; list1.size()) {
                    list2.add(list1.get(i));
                    recurse(i + 1);
                }
            }
        }.recurse(0);
    
        System.out.println("List 1:");
        for (final String s : list1)
            System.out.println("\t" + s);
    
        System.out.println("List 2:");
        for (final String s : list2)
            System.out.println("\t" + s);
    }
    

    }

    Programme withdrawal:

    List 1:
    String 1
    String 2
    String 3
    List 2:
    String 1
    String 2
    String 3


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2