如何从LinkedList中打印指定元素?提取关联存储的IP地址
Hey there! I see you're trying to pull out and print IP addresses stored alongside PC identifiers in a LinkedList of PlsWork objects. Let's walk through exactly how to do this step by step.
First, let's round out your PlsWork class (I'll fill in that incomplete toString() method for you—it'll make printing way cleaner):
import java.net.InetAddress; public class PlsWork { private InetAddress IP; private String PC; public PlsWork(InetAddress IP, String PC) { this.IP = IP; this.PC = PC; } public InetAddress getIP() { return IP; } public String getPC() { return PC; } @Override public String toString() { // Returns a readable format for each device entry return "PC: " + PC + ", IP Address: " + IP.getHostAddress(); } }
Option 1: Print Full PC + IP Pairs
If you want to print both the PC identifier and its linked IP, you can just iterate over the LinkedList and print each PlsWork object directly. Your overridden toString() will handle the formatting automatically:
import java.net.InetAddress; import java.net.UnknownHostException; import java.util.LinkedList; public class DevicePrinter { public static void main(String[] args) { LinkedList<PlsWork> deviceList = new LinkedList<>(); // Add sample devices to the list (handle the hostname resolution exception!) try { deviceList.add(new PlsWork(InetAddress.getByName("192.168.1.100"), "PC1")); deviceList.add(new PlsWork(InetAddress.getByName("192.168.1.101"), "PC2")); deviceList.add(new PlsWork(InetAddress.getByName("10.0.0.5"), "PC3")); } catch (UnknownHostException e) { e.printStackTrace(); } // Iterate and print each device's full info System.out.println("All Devices & Their IPs:"); for (PlsWork device : deviceList) { System.out.println(device); } } }
Option 2: Print Only the IP Addresses
If you just need the raw IP strings without the PC labels, use the getIP() method from your PlsWork class, then call getHostAddress() on the InetAddress object. This gives you the numeric IP (instead of the default InetAddress.toString() which includes the hostname):
// Inside the main method after populating the list System.out.println("\nJust the IP Addresses:"); for (PlsWork device : deviceList) { String rawIp = device.getIP().getHostAddress(); System.out.println(rawIp); }
Option 3: Java 8+ Stream Approach (Shorter Syntax)
If you're using Java 8 or later, streams make the iteration even more concise:
// Print full device details System.out.println("\nStream - Full Device Info:"); deviceList.forEach(System.out::println); // Print only IP addresses System.out.println("\nStream - Just IPs:"); deviceList.stream() .map(device -> device.getIP().getHostAddress()) .forEach(System.out::println);
Quick Tips:
- Don't forget to handle
UnknownHostExceptionwhen usingInetAddress.getByName()—this gets thrown if the IP/hostname can't be resolved. - Use
getHostAddress()whenever you want just the numeric IP (no extra hostname text attached).
内容的提问来源于stack exchange,提问作者obinna

