Created
February 22, 2024 21:50
-
-
Save cmoz/a57a8edf52bca60ec6e2d25c03f01ef6 to your computer and use it in GitHub Desktop.
LinkedList example and overriding the toString() method
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
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