Java Enumeration接口详解

本文详细介绍了枚举接口的实现原理及使用方法,并通过Vector的elements方法进行实例演示。此外,还对比了枚举接口与迭代器接口的区别,指出迭代器接口在功能上的优势。

二话不说,来看官方文档:

public interface Enumeration<E>
An object that implements the Enumeration interface generates a series of elements, one at a time.
Successive calls to the nextElement method return successive elements of the series.
实现了枚举接口的对象会生成一系列元素,一次一个。通过连续的调用nextElement方法获得连续的元素。

拿vector的elements方法源码举例:

public Enumeration<E> elements() {
        //通过匿名类方式实现了Enumeration接口
        return new Enumeration<E>() {
            int count = 0;

            public boolean hasMoreElements() {
                return count < elementCount;
            }

            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }



For example, to print all elements of a Vector<E> v:

   for (Enumeration<E> e = v.elements(); e.hasMoreElements();)
       System.out.println(e.nextElement());
Methods are provided to enumerate through the elements of a vector, the keys of a hashtable, and the values in a hashtable.
Enumerations are also used to specify the input streams to a SequenceInputStream.

NOTE: The functionality of this interface is duplicated by the Iterator interface.
In addition, Iterator adds an optional remove operation, and has shorter method names.
New implementations should consider using Iterator in preference to Enumeration.
说明:本接口功能已被Iterator接口取代。Iterator接口扩展了删除方法,并且具有更简洁的方法名。


再来写个实例,加深了解:


package com.dylan.collection;

import java.util.Enumeration;
import java.util.Vector;

/**
 * 测试枚举接口,
 * 可用于遍历集合类型,目前已被迭代器Iterator取代
 *
 * @author xusucheng
 * @create 2017-12-25
 **/
public class EnumerationTest {
    public static void main(String[] args) {
        Vector v = new Vector();
        v.add("Jack");
        v.add("ate");
        v.add("lots of oranges.");
        Enumeration<String> e = v.elements();
        String output = "";
        while (e.hasMoreElements()) {
            output += e.nextElement() + " ";
        }

        System.out.println(output);
    }
}
















package com.example.netportnew; import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Collections; import java.util.Enumeration; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView netPortData = findViewById(R.id.NetPortData); netPortData.setText(getNetworkInterfacesInfo()); TextView netPortIPData = findViewById(R.id.NetPortIPData); netPortIPData.setText(getActiveNetworkIP()); } //获取网络信息 private String getNetworkInterfacesInfo() { StringBuilder sb = new StringBuilder(); try { // 获取所有网络接口 Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netInterface : Collections.list(interfaces)) { // 获取接口名称 String interfaceName = netInterface.getName(); sb.append("Interface: ").append(interfaceName).append("\n"); // 获取接口显示名称(可能为null) String displayName = netInterface.getDisplayName(); if (displayName != null) { sb.append("Display Name: ").append(displayName).append("\n"); } // 获取IP地址 Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); sb.append("IP: ").append(address.getHostAddress()).append("\n"); } sb.append("\n"); // 添加空行分隔不同接口 } } catch (SocketException e) { e.printStackTrace(); return "Error getting network info: " + e.getMessage(); } // 如果没有获取到任何信息 if (sb.length() == 0) { return "No network interfaces found"; } return sb.toString(); } //仅获取活动网络IP private String getActiveNetworkIP() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) { return "接口: " + intf.getName() + "\nIP: " + inetAddress.getHostAddress(); } } } } catch (SocketException ex) { ex.printStackTrace(); } return "无法获取IP地址"; } } 获取所有网口,若没有IP则显示未连接
最新发布
08-13
你当前的代码已经可以获取所有网口及其 IP 地址信息,但目前在没有 IP 的情况下(如网口未连接),并没有明确提示“未连接”,而是直接跳过了。 --- ## ✅ 目标改进 我们要实现: - 显示所有网口; - 若某网口 **没有 IP 地址**,则显示:`未连接`; - 同时保留已有的 IP 地址显示逻辑。 --- ## ✅ 修改后的完整代码如下: ```java // 获取所有网络接口并显示信息(无IP则显示“未连接”) private String getNetworkInterfacesInfo() { StringBuilder sb = new StringBuilder(); try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netInterface : Collections.list(interfaces)) { String interfaceName = netInterface.getName(); sb.append("接口: ").append(interfaceName).append("\n"); String displayName = netInterface.getDisplayName(); if (displayName != null) { sb.append("显示名称: ").append(displayName).append("\n"); } Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); boolean hasIp = false; while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()) { sb.append("IP: ").append(address.getHostAddress()).append("\n"); hasIp = true; } } // 如果没有有效的IP地址,显示“未连接” if (!hasIp) { sb.append("状态: 未连接\n"); } sb.append("\n"); // 分隔不同网口 } } catch (SocketException e) { e.printStackTrace(); return "获取网络信息失败: " + e.getMessage(); } if (sb.length() == 0) { return "未检测到网络接口"; } return sb.toString(); } ``` --- ## ✅ 效果说明 - 若某网口有 IP 地址(非回环、非本地链路):显示 `IP: xxx.xxx.xxx.xxx` - 若某网口 **没有有效 IP**:显示 `状态: 未连接` - 所有网口都会列出,不会跳过 --- ## ✅ 示例输出 ``` 接口: wlan0 显示名称: wlan0 IP: 192.168.1.100 接口: eth0 显示名称: eth0 状态: 未连接 接口: lo 显示名称: localhost IP: 127.0.0.1 ``` --- ## ✅ 可选增强功能 你可以进一步扩展功能,比如: - 区分 Wi-Fi、以太网、蓝牙等类型; - 检测网口是否处于 UP 状态; - 显示 MAC 地址; - 显示子网掩码等信息。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值