如何从Java中的对象向量中获取特定的类型对象 [英] How to get a specific type object from an Object Vector in Java

查看:353
本文介绍了如何从Java中的对象向量中获取特定的类型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的 Vector ,并且在运行时我要传递一个整数字符浮点数

  public static Vector< Object> interestingValues = new Vector< Object>(); 

同时我想得到整数 Float ,或 Character ,所以有两件事情:




  • 它们是否保留了特定的整数 / Float / Character 输入 Object Vector ,或者所有将以 Object ?形式存储。

  • 如何检索整数从这个 Vector的对象




$ b

 整数i =(整数)interestingValues.get( 0); 

如果Vector中有多种类型的对象,可以使用 instanceof

  Object o = interestingValues.get(0); 
if(o实例的整数){
整数i =(整数)o;
} else if(o instanceof Long){
Long l =(Long)o;



$ b $ p
$ b

你可以做的第三件事是避免需要把对象转换成特定的类型正在使用类型为 Vector

  Vector< Integer> integerVector = new Vector< Integer>(); 
integerVector.add(Integer.MAX_VALUE);
Integer i = integerVector.get(0);


I have the following Vector and at runtime I want to pass it an Integer, Character, or Float:

public static Vector<Object> interestingValues = new Vector<Object>();

At the same time I want to get an Integer, Float, or Character from it, so there are two things:

  • Will they retain the specific Integer/Float/Character type in the Object Vector, or they all will be stored in the form of Object?

  • How can I retrieve Integer objects from this Vector?

解决方案

Casting:

Integer i=(Integer)interestingValues.get(0);

In case you have multiple types of objects inside the Vector you could check the type using instanceof:

Object o=interestingValues.get(0);
 if (o instanceof Integer){
      Integer i=(Integer)o;
 }else if (o instanceof Long){
      Long l=(Long)o;
 }

The third thing you can do to avoid the need ov casting objects to a particular type is using a typed Vector:

Vector <Integer> integerVector=new Vector<Integer>();
integerVector.add(Integer.MAX_VALUE);
Integer i=integerVector.get(0);

这篇关于如何从Java中的对象向量中获取特定的类型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆