HashSet<String> myHashSet = new HashSet<String>(); myHashSet.add("Belgium"); myHashSet.add("France"); myHashSet.add("Italy"); myHashSet.add("Germany");
myHashSet.size();
Iterator itr = myHashSet.iterator(); while(itr.hasNext()) { // itr.next().toString() // txtView2.setText(txtView2.getText() + itr.next().toString() + ","); }
if (myHashSet.contains("Italy")) { // Already member }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="22dp" android:text="TextView" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/textView1" android:layout_marginTop="20dp" android:text="TextView" /> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginTop="150dp" > </ListView> </RelativeLayout>
package com.myapp; import java.util.HashSet; import java.util.Iterator; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends Activity { ArrayAdapter<String> adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /**** Sample 1 ****/ HashSet<String> myHashSet = new HashSet<String>(); myHashSet.add("Belgium"); myHashSet.add("France"); myHashSet.add("Italy"); myHashSet.add("Germany"); // Get Size HashSet final TextView txtView1 = (TextView)findViewById(R.id.textView1); txtView1.setText("HashSet Size = " + myHashSet.size()); // Loop Data HashSet final TextView txtView2 = (TextView)findViewById(R.id.textView2); txtView2.setText(""); Iterator itr = myHashSet.iterator(); while(itr.hasNext()) { txtView2.setText(txtView2.getText() + itr.next().toString() + ","); } // Convert HashSet to Array String[] myArr = {}; myArr = myHashSet.toArray(new String[myHashSet.size()]); // Show Array to ListView final ListView lView = (ListView)findViewById(R.id.listView1); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myArr); lView.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท