Created
May 9, 2013 08:21
-
-
Save YukiYoshikawa/5546241 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package trial.yy.guava.client.collect; | |
import com.google.common.collect.ImmutableSet; | |
import java.util.Collections; | |
import java.util.LinkedHashSet; | |
import java.util.Set; | |
/** | |
* com.google.common.collect.ImmutableSetを試すためのサンプル | |
* User: yy | |
*/ | |
public class ImmutableSetClient { | |
public static void main(String[] args) { | |
// Collections#unmodifiableSetとImmutableSet#copyOfで生成したSetの動きの違いを確認 | |
System.out.println("### Difference between Collections#unmodifiableSet and ImmutableSet#copyOf"); | |
Set<String> names = new LinkedHashSet<>(); | |
names.add("taro"); | |
names.add("jiro"); | |
Set<String> setBuiltIn = Collections.unmodifiableSet(names); | |
Set<String> setGuava = ImmutableSet.copyOf(names); | |
names.add("saburo"); | |
// 生成元のSetに対して要素を追加してもImmutableSetには追加されない | |
System.out.println("Built In Set: " + setBuiltIn); // -> [taro, jiro, saburo] | |
System.out.println("Guava Set: " + setGuava); // -> [taro, jiro] | |
System.out.println("### ImmutableSet#of"); | |
ImmutableSet<Integer> set1 = ImmutableSet.of(1, 2, 3, 4); | |
try { | |
set1.add(5); | |
} catch (UnsupportedOperationException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("set1: " + set1); | |
// ImmutableSet.Builderを使って元のSet+新しい要素のImmutableSetを生成 | |
System.out.println("### ImmutableSet.Builder#build"); | |
Set<String> set = ImmutableSet.of("ABC", "DEF", "GHI"); | |
ImmutableSet<String> setStrGuava = new ImmutableSet.Builder<String>() | |
.addAll(set) | |
.add("JKL") | |
.build(); | |
System.out.println("setStrGuava: " + setStrGuava); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment