Skip to content

Instantly share code, notes, and snippets.

@cmoz
Created February 22, 2024 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmoz/a57a8edf52bca60ec6e2d25c03f01ef6 to your computer and use it in GitHub Desktop.
Save cmoz/a57a8edf52bca60ec6e2d25c03f01ef6 to your computer and use it in GitHub Desktop.
LinkedList example and overriding the toString() method
import java.util.LinkedList;
class ProductItem {
private int productId;
private String productName;
public ProductItem(int productId, String productName) {
this.productId = productId;
this.productName = productName;
}
public int getProductId() {
return productId;
}
public String getProductName() {
return productName;
}
@Override
public String toString() {
return "Product{" +
"productId=" + productId +
", productName='" + productName + '\'' +
'}';
}
}
public class Main2 {
public static void main(String[] args) {
// Create a linked list of products
LinkedList<ProductItem> productList = new LinkedList<>();
// Add some products
productList.add(new ProductItem(101, "Smartphone"));
productList.add(new ProductItem(102, "Laptop"));
productList.add(new ProductItem(103, "Headphones"));
// Display the linked list
System.out.println("Linked List of Products:");
for (ProductItem product : productList) {
System.out.println(product);
}
// Add a new product at the beginning
productList.addFirst(new ProductItem(100, "Tablet"));
// Remove the last product
productList.removeLast();
// Display the updated linked list
System.out.println("\nUpdated Linked List of Products:");
for (ProductItem product : productList) {
System.out.println(product);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment