【问题标题】:Extract the Map <K,V> an object of type parameters passed提取 Map <K,V> 传递的类型参数的对象
【发布时间】:2012-01-25 00:11:05
【问题描述】:

我得到一个对象作为参数,并想将对象的键与字符串数组进行比较。

对象的类型为Map &lt;String, byte[]&gt;

String [] keys = {"a", "b"}

抱歉缺席,我没有机会来这里,所以我会尽力解释我想要什么。我通过套接字接收一个对象,然后通过对象参数传递给方法readObject。

Map 在这种方法中,我必须将“K”(键)分开并将它们插入到不同的 Map 中。例如:

Map 1 (String [] = {1 map "a", "f", "c", "d"};

Map 2 (String [] {map = 2 "and", "i", "o", "k"};

main class

{ //...

S.getInputStream InputStream is =..... ();

ObjectInputStream ois = new ......;

MapObject mo = (MapObject) ois.readObject ();

//-----> ReadObject (mo)

... }

public static MapObject readObject (MapObject mo) {

String [] map1 = { "a", "f", "c", "d"};

有可能吗? ----> MapObject mapi = mo;

他在下一步爆发

这------->

Map map = (Map ) mo;

    for (Map.Entry entry : map.entrySet ()) {

     Entry.getKey key = String ();

     byte [] value = entry.getValue ();

     if (test.equals (entry.getKey ()))
     {

          map.put (key, value);
      }

        }

    } 
    public void readObject(Object parObj)
    {

      Here I want to extract the key from parObj comparable to do with the String []

      for example an if ().

      finally extract unable to insert a value to put (Key, Value);

    }

我的难点在于提取key和value。

实现我的目标的一些建议或提示?

感谢您的关注和有空

【问题讨论】:

  • 为什么不直接把参数的类型改成Map&lt;String, byte[]&gt;
  • 我得解释一下。我需要传递套接字对象,然后使用将字符串和值作为参数的 put 方法。
  • 您需要提供更多细节并更好地解释它。到目前为止的帖子真的很混乱。
  • @Jeffrey:我猜java.io.Serializable在这里起了作用。
  • @BalusC 这就是我的想法,但由于 OP 从未真正说过,我不想做出错误的假设。

标签: java map hashmap


【解决方案1】:

如果我理解了这个问题,您首先需要将对象转换为Map,以便您可以使用地图交互,然后您可以遍历所有条目并执行您需要的任何操作。

Map<String, byte[]> m = (Map)parObj;
for (Map.Entry<String, byte[]> entry : m.entrySet()) {
  String key = entry.getKey();
  byte[] value = entry.getValue();
  // do whatever you need with the key and value...
}

【讨论】:

  • 成功帮了我很多忙!谢谢
  • @user1155232 很高兴我能提供帮助,如果你觉得它有用,你可以接受这个答案。
【解决方案2】:

对此进行澄清可能会有所帮助;我真的不明白你在追求什么。

地图的javadoc是here

也就是说,这是我最好的选择。

另外,正如@Jeffrey 所说,您应该传递一个地图,而不是一个对象。

public void class Foo{
    private String[] keys  {"a", "b"};

    public void readObject(Map<String, byte[]> parObj){
        boolean foundAnyKey = false;
        for(String key : keys){
            if(parObj.containsKey(key) == true){
                 foundAnyKey = true;
                 byte[] values = parObj.get(key);
                 *<do something special with the values>*
            }
        }

        if(foundAnyKey == true){
           *<do something special, 'cause you found a key>*
        }//--for(...)

    }//--readObject(...)
}//--Foo{..}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2019-10-10
    • 2021-12-03
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多