Java从Hashmap获取最后一个键

Gum*_*lar 1 java android hashmap

以前,如果我的问题很经典,我表示歉意。但是因为我刚刚学习了android的Java编程,我并没有真正理解命令。

我目前正在使用代码部分制作一个应用程序,如下所示:

Map<Integer, CompTypes> mapCompTypes = new java.util.HashMap();

class CompTypes
{
    int androidId;
    AndroidViewComponent component;
    String text;
    String type;
    CompTypes(int androidId, AndroidViewComponent component, String type, String text)
    {
        this.androidId = androidId;
        this.component = component;
        this.type = type;
        this.text = text;
    }
}

public void SendMessage(HVArrangement container, String message, String dateTime, int fontSize, int fontColor, int alignment, int startid)
{
    int id = Integer.parseInt(ChatBox.this.GetLastId());
    TextBox comp = new TextBox(vertical);
    comp.getView().setId(id);
    comp.Text(message);
    comp.FontSize(fontSize);
    comp.TextColor(fontColor);
    comp.MultiLine(true);
    comp.Enabled(false);
    comp.RequestFocus();
    mapCompTypes.put(Integer.valueOf(id), new CompTypes(id, comp, compType, comp.Text()));

    int id2 = id + 1;
    Label dt = new Label(vertical);
    dt.getView().setId(id2);        
    ((TextView)dt.getView()).setText(android.text.Html.fromHtml(datetime));
    dt.HTMLFormat(true);
    dt.Text(datetime);
    dt.getView().setOnClickListener(this);
    dt.getView().setOnLongClickListener(this);
    mapCompTypes.put(Integer.valueOf(id2), new CompTypes(id2, dt, compType, dt.Text()));
}


public String GetLastId()
{
    // how to get last id?
    //return ids;
}
Run Code Online (Sandbox Code Playgroud)

目前我无法从 id 获取值作为来自 Hashmap 的最后一个 id。我在这里阅读了许多问题和答案,“地图没有最后一个条目,这不是他们合同的一部分。” 有没有另一种方法可以获得最后一个ID?

Zai*_*rza 6

HaspMap 不保留顺序。因此,不可能通过最后、第一或中间位置获取任何元素。

您可以做的一件事是key在插入HashMap并访问该变量以获取最后一个对象的键时将您的变量保存在某个变量中。对于保证订单,您还可以查找LinkedHashMap