这是一个非常基本的测试程序:
public class Body implements Serializable {
static int bod = 5;
int dis = -1;
public void show(){
System.out.println("Result: " + bod + " & " + dis);
}
}
public class Testing {
public static void main(String[] args) {
Body theBody = new Body();
theBody.show();
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.dat"));
out.writeObject(theBody);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.dat"));
Body bodyDouble = (Body)in.readObject();
in.close();
bodyDouble.show();
} catch(IOException e) {
} catch(ClassNotFoundException e) {
}
}
} …Run Code Online (Sandbox Code Playgroud) 假设我们有一个类World,我们已经声明了dreamWorld该类的实例.情况1如何与案例2不同,除了它的一条线更短?在第二种情况下实例化实际上有什么区别?我的意思是,dreamWorld在这两种情况下,afterall 都是一样的,对吧?
案例1:
void changeWorld(World outerWorld) {
World dreamWorld;
dreamWorld = outerWorld;
}
Run Code Online (Sandbox Code Playgroud)
案例2:
void changeWorld(World outerWorld) {
World dreamWorld;
dreamWorld = new World();
dreamWorld = outerWorld;
}
Run Code Online (Sandbox Code Playgroud)
where outerWorld是World在别处创建的类的对象,比如说,作为方法参数提供(我不确定它是如何提供的重要).
PS 谢谢你所有的提示和有用的回复,伙计们,对不起我的延迟感谢(我花了很多时间阅读一些我觉得有必要完全理解你的回复的文献).
我有一个HashMap<Float[], Integer>,我可能需要将其转换为TreeMap.如何对TreeMap的键(即数组)进行排序?他们的第一个元素?
我打算运行一个简单的测试,但它以某种方式导致错误:
public class treeMapTest {
public static void main(String[] args) {
Integer arr1[] = {9, 0, 3};
Integer arr2[] = {2, 2, 2};
Integer arr3[] = {4, 2, 1};
TreeMap<Integer[], Integer> tm = new TreeMap<Integer[], Integer>();
tm.put(arr1, 7);
tm.put(arr2, 7);
tm.put(arr3, 7);
System.out.println(tm);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
我一直在使用一个类:
public class Change {
Object affectedObj; //takes an instance of any class
String affectedFieldName;
float shift;
...
public void apply() {
affectedObj.getClass().getField(affectedFieldName).setFloat(affectedObj, shift);
}
}
Run Code Online (Sandbox Code Playgroud)
我现在需要序列化。由于Object不可序列化,如何使我的类可序列化?
我想到的一件事是Object用泛型<T>类型替换:
public class Change<T> {
T affectedObj; //takes an instance of any class
String affectedFieldName;
float shift;
...
public void apply() {
affectedObj.getClass().getField(affectedFieldName).setFloat(affectedObj, shift);
}
}
Run Code Online (Sandbox Code Playgroud)
但我无法判断这种方法的缺点。如果这是一个好方法,那么这里关于序列化的陷阱是什么?
聚苯乙烯
谢谢各位大佬的回复。他们都对我很有启发性和帮助。
我需要写一些方法来完成一件事,我不知道该怎么做.我很感激任何帮助.
假设我们有一个void m1(int z) {}
这样调用的方法
:
int x; ... m1(x);
基本上我需要确保方法m1正好使用我需要的'x'字段.不是'x'字段的值,而是指向字段'x',而不是指向此字段或任何其他类的其他字段.
更具体地说,我打算写一个if语句意思:
if (z is pointing to the field x) return true;
我不知道如何实现指向条件.有这种评估的标准方法吗?
非常感谢你的答复,你们所有人.
@durbnpoisn,@ Boris the Spider
代码本身尚不存在,但我正在尝试详细说明这些方法.我不是一个经验丰富的程序员,这就是为什么它可能看起来很奇怪.对不起.
但是,如果它有助于我的任务是制作几个"切换"按钮,当按下这些按钮时,从代码的不同部分切换掉某些字段和方法,就好像它们从未使用过一样.
例如,代码行看起来像supCrossVal = x^realOpt/setPower(mine)所有开关关闭,它应该像supCrossVal = x^realOptSWITCH1打开时那样执行.
问题是初始代码非常大(因此相关调用的数量)和开关数量大约为10-15,并且一些swithes可以关闭相同的方法和字段.因此,在我看来,为每个字段或方法调用添加if语句(检查开关是打开还是关闭)将使代码难以阅读.并且每个交换机的重载方法看起来过于简单,代码也乱丢垃圾.所以我在考虑一种基于指向思想的简单方法.