Judita
Judita

Reputation: 119

Convert CustomList to String/Array

I have a CustomList which does everything as needed until I encountered that code like String.join(" ", list) or list.toArray(String[]::new) doesn't work with my CustomList but works with ArrayList. What am I doing wrong?

CustomList adds and removes every element in pairs.

class CustomList implements List<String> {

    private List<String> list;

    public CustomList() {
        list = new ArrayList<String>();
    }

//implemented overridden methods
}

String.join(" ", list) throws a NullPointerException. list.toArray(String[]::new) returns null.

    public <T> T[] toArray(T[] a) {
        list.toArray(a);
        return a;
    }

    public Iterator<String> iterator() {
        return list.iterator();
    }

Upvotes: -1

Views: 113

Answers (1)

Most Noble Rabbit
Most Noble Rabbit

Reputation: 2776

list.toArray(String[]::new) doesn't compile for me. Perhaps, the way you use the class is wrong.

I implemented the methods:

@Override
public Iterator<String> iterator() {
    return list.iterator();
}

@Override
public <T> T[] toArray(T[] a) {
    return list.toArray(a); // Better not to return a, but should work either way.
}

Then I tested the CustomList:

CustomList strings = new CustomList();
strings.addAll(Arrays.asList("A", "B", "C"));

Iterator<String> iterator = strings.iterator();
String firstStr = iterator.next();
System.out.println("Iterator test: "+ firstStr);

String[] arr = new String[strings.size()];
strings.toArray(arr);
System.out.println("toArray() test: "+ Arrays.toString(arr));

String join = String.join(" ", strings);
System.out.println("String.join test: "+join);

Output:

Iterator test: A
toArray() test: [A, B, C]
String.join test: A B C

Upvotes: 0

Related Questions