简体   繁体   中英

Got an error message: error: 'void' type not allowed here

First I have a class and the class has a void method:

class IntGroup {
        int size;
        List<int[]> intervals;
        public IntGroup() {
            this.size = 0;
            this.intervals = new ArrayList<>();
        }
        
        public void addInt(int[] interval) {
            this.intervals.add(interval);
            this.size++;
        }
    }

Then when I try to create a List, create a new object and call the method

// int[][] intervals
List<IntGroup> list = new ArrayList<>();
list.add(new IntGroup().addInt(intervals[0]));

I got error message error: 'void' type not allowed here list.add(new IntGroup().addInt(intervals[0])); . I tried to change the return type of addInt to List and int , neither worked.

You're calling list.add with "whatever is returned from the addInt method"... but the addInt method is declared with a void return type... it doesn't return anything, so you can't use the return value.

Two options to fix this:

1) Change addInt to return IntGroup :

public IntGroup addInt(int[] interval) {
    this.intervals.add(interval);
    this.size++;
    return this;
}

At this point, the existing list.add call is valid, because addInt returns an IntGroup - the same reference it was called on.

This is a reasonably common pattern in some APIs, such as StringBuilder , but it's not clear that it's appropriate here.

2) Separate out the list.add call from the addInt call

Just use a local variable to "remember" the group you're working with:

IntGroup group = new IntGroup();
group.add(intervals[0]);
list.add(group);

addInt Returns void and you try to add it to the list:

new IntGroup().addInt(intervals[0]); <-- this is a void because addInt returns void

Try this instead:

// int[][] intervals
List<IntGroup> list = new ArrayList<>();
IntGroup intGroup = new IntGroup();
intGroup.addInt(intervals[0]);
list.add(intGroup);

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