```java public class ExampleMethod5 { public static void main(String[] args) { /* * 這次的方法使用場景比較進階一點。 * * 當你可能遇到同樣名稱的方法名稱都要傳入相同的參數構造跟數量, * 但只差在 List 承載的物件類型不同時,就可以考慮這麼處理。 */ List<String> list = new ArrayList<>(); list.add("str"); List<Integer> list2 = new ArrayList<>(); list2.add(123); List<Object> list3 = new ArrayList<>(); list3.add("str"); list3.add(123); test1(list); test1(list2); test1(list3); test2(list); test2(list2); test2(list3); // 以上那些程式,使用比較偷懶的寫法 // test1(new ArrayList<String>() {{ add("str"); }}); // test1(new ArrayList<Integer>() {{ add(123); }}); // test1(new ArrayList<Object>() {{ add(123); add("str"); }}); // test2(new ArrayList<String>() {{ add("str"); }}); // test2(new ArrayList<Integer>() {{ add(123); }}); // test2(new ArrayList<Object>() {{ add(123); add("str"); }}); } public static <T> void test1(List<T> list) { for (T t : list) { if (t instanceof String) { System.out.println(t + " is string"); } else if (t instanceof Integer) { System.out.println(t + " is int"); } } } public static void test2(List<?> list) { for (Object t : list) { if (t instanceof String) { System.out.println(t + " is string"); } else if (t instanceof Integer) { System.out.println(t + " is int"); } } } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up