简体   繁体   中英

What is the datatype of a Java varargs (…) parameter?

I am trying to add information from main() to a items class where i am storing the information in a hashset

i have 3 classes

  1. project - main()

  2. libaray - addBandMembers function

  3. Item - addband(String... member)

i am adding CD information. first, i add band, # of songs, title - which works good

then in another function i am trying to add the band members. I want to keep these separate. Where i am having problems is assign the band members..

I understand that how Varargs works just not sure how to assign that to a string..

I will only show bits of code to keep this post simple and short..

this is what i have:

Main()

item = library.addMusicCD("Don't Let Go", "Jerry Garcia Band", 15, "acid rock", "jam bands");
if (item != null) {
library.addBandMembers(item, "Jerry Garcia", "Keith Godcheaux");
library.printItem(out, item);
}

Then, here the first function thats called..

public void addBandMembers(Item musicCD, String... members)
{

   //musicCD.addband(members);   // both cant find addband function..
    //Item.addband(members);

}

Then in another class i am trying to add the information..

 private String members;  


public void addband(String... member)
{
    this.members = member;     // error

}

if i make the private String members; an array then this function below errors.. incompatible type..

 public String getMembers()
{
 return members;   
}

How can i do this?

oh ya, here is my set..

public class Library
{
private Set<CD> theCDs = new HashSet<CD>();
private Set<DVD> theDVDs = new HashSet<DVD>();
private Set<Book> theBooks = new HashSet<Book>();

if you need to see more code let me know.. Thank you so much..

A varargs argument resolves to an array .

So, change

private String members;  

to

private String[] members;  

更改getter以返回String数组而不是String。

String... member gives you an array, so what you are looking at is a member that is of type String[].

I think once you get that, you kind of get over the hump of the issue.

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