As shown in this video, the main difference are:
Set:
- every element is unique
- not ordered
List:
- can repeat the same element
- ordered
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com
Complete source code and other details:
package com.programmerworld.listvsset;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView textViewSet, textViewList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewList = findViewById(R.id.textViewList);
textViewSet = findViewById(R.id.textViewSet);
}
public void buttonDisplay(View view){
Set<String> stringsSet = new HashSet<>();
stringsSet.add("Paris");
stringsSet.add("Tokyo");
stringsSet.add("Beijing");
stringsSet.add("Seoul");
stringsSet.add("Tokyo");
textViewSet.setText(stringsSet.toString());
List<String> stringsList = new ArrayList<>();
stringsList.add("Paris");
stringsList.add("Tokyo");
stringsList.add("Beijing");
stringsList.add("Seoul");
stringsList.add("Tokyo");
textViewList.setText(stringsList.toString());
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textViewSet"
android:layout_width="290dp"
android:layout_height="175dp"
android:text="Display Set"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.028" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="156dp"
android:layout_marginTop="36dp"
android:onClick="buttonDisplay"
android:text="Display"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewList" />
<TextView
android:id="@+id/textViewList"
android:layout_width="289dp"
android:layout_height="159dp"
android:layout_marginStart="60dp"
android:layout_marginTop="32dp"
android:text="Display List"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewSet" />
</androidx.constraintlayout.widget.ConstraintLayout>
With Duplicate entry of “Tokyo”
Without any duplicate entry: