Reputation: 2497
I would like to implement a method isInBlackList(String element)
, which return true, if element
is founded in the blacklist. I have the following code:
public boolean isInBlackList(String element) {
Set<String> blackList = new HashSet<String>();
blackList.add("element1");
blackList.add("element2");
...
.....
blackList.add("element20");
return blackList.contains(element);
}
What is bothering me is that I have to write add()
method 20 times. Any better idea? it does not have to be implemented with Set
.
Upvotes: 1
Views: 5427
Reputation: 8466
Try this way,
Set<String> blackList = new HashSet<String>();
public static void main(String[] args)
{
Test12 ss = new Test12();
ss.populateBlackList(); // if the blacklist is fixed means you can call this in constructor
System.out.println(ss.isInBlackList("element1"));
}
private void populateBlackList() // make it as an seperate method dont populate at all time
{
for (int i = 1; i <= 20; i++)
{
blackList.add("element" + i);
}
}
public boolean isInBlackList(String element) //finding the blackList
{
return blackList.contains(element);
}
Upvotes: 1
Reputation: 831
You can make blacklist
a field of your class and initialize it with :
Set<String> blackList = new HashSet<String>(Arrays.asList("element1", ...));
Upvotes: 1
Reputation: 172528
You may try like this:
Set<String> blackList = new HashSet<String>(Arrays.asList("element1", "element2", "element3"));
Upvotes: 3
Reputation: 9628
The simplest way I can think of is the following:
final List<String> blackList = Arrays.asList("element1", "element2", "element3");
As you can see, that's... really minimalist, and still works :)
Upvotes: 2
Reputation: 54692
declare blackList as a member variable and initialize it in constructor.
just use a for loop to add the elements
for( int i = 1; i<=20; i++){
string s = "element"+i;
blackList.add(s);
}
Upvotes: 0