You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让调试器正确显示List的子类BetterList?

Absolutely! You can absolutely tweak how your BetterList class shows up in debuggers by overriding certain methods or using debugger-specific annotations. Here are the most effective approaches:

1. Override the toString() Method

This is the most universal approach—nearly every debugger uses the toString() output to display a human-readable representation of an object. By default, Java's Object.toString() returns something like BetterList@12345678, which isn't helpful for debugging.

Instead, override it to mirror how standard List implementations (like ArrayList) display their contents:

public class BetterList<E> extends ArrayList<E> {
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("BetterList[");
        for (int i = 0; i < size(); i++) {
            if (i > 0) {
                sb.append(", ");
            }
            sb.append(get(i));
        }
        sb.append("]");
        return sb.toString();
    }
}

Now your debugger will show the actual elements in your BetterList instead of a generic hash code.

2. Use Debugger-Specific Annotations (For IDE Customization)

If you want more control over the debug display without altering the toString() behavior (which might be used elsewhere in your code), most popular IDEs offer custom annotations to define debug-only representations:

For IntelliJ IDEA:

Use the @DebuggerDisplay annotation from the IntelliJ SDK. You can specify exactly what fields or method results to show:

import com.intellij.debugger.DebuggerDisplay;

@DebuggerDisplay("BetterList (size: {size()}, elements: {toString()})")
public class BetterList<E> extends ArrayList<E> {
    // Your custom logic here
}

This will make the debugger show a formatted string with the list size and elements, without changing how toString() works for regular code execution.

For Eclipse:

Eclipse uses the @org.eclipse.debug.ui.DebuggerDisplay annotation, which works similarly. Define a string pattern that references your class's methods or fields:

import org.eclipse.debug.ui.DebuggerDisplay;

@DebuggerDisplay("BetterList: size={size}, elements={toString()}")
public class BetterList<E> extends ArrayList<E> {
    // Your custom logic here
}
3. Ensure Core List Methods Are Properly Implemented

If your BetterList extends a base class like AbstractList instead of ArrayList, make sure you've correctly implemented the mandatory methods: size() and get(int index). Debuggers often rely on these methods to iterate over and display list elements—if they're broken, the debugger might show empty or incorrect content even if your list holds valid data.


内容的提问来源于stack exchange,提问作者JavaJawa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:02:42