Java的编程代码语言中怎么对两个结构体的类型的变量,变量的内容的大小进行一个判断的操作最好是用方法函数实现,具体的实现步骤
如图:
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) {
// 创建两个结构体对象
MyStruct struct1 = new MyStruct(10, "Hello");
MyStruct struct2 = new MyStruct(20, "World");
// 调用方法进行变量判断
boolean result = compareStructs(struct1, struct2);
System.out.println("两个结构体变量的内容是否相同:" + result);
}
// 自定义结构体
static class MyStruct {
private int intValue;
private String stringValue;
public MyStruct(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
}
// 方法函数,比较两个结构体变量的内容大小
public static boolean compareStructs(Object struct1, Object struct2) {
// 获取结构体的Class对象
Class<?> structClass = struct1.getClass();
try {
// 遍历结构体的字段
for (Field field : structClass.getDeclaredFields()) {
// 设置允许访问私有字段
field.setAccessible(true);
// 获取字段的值
Object value1 = field.get(struct1);
Object value2 = field.get(struct2);
// 比较字段的值
if (!value1.equals(value2)) {
return false; // 内容不相同,返回false
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return true; // 所有字段内容相同,返回true
}
}
public struct Point {
int x;
int y;
}
public struct Size {
int width;
int height;
}
public static boolean compareStructs(Point p1, Point p2) {
if (p1.x != p2.x || p1.y != p2.y) {
return false;
} else {
return true;
}
}
Point p1 = new Point(10, 20);
Point p2 = new Point(5, 15);
Size size1 = new Size(400, 300);
Size size2 = new Size(600, 400);
System.out.println("p1 and p2 are the same size? " + compareStructs(p1, p2)); // true
System.out.println("size1 and size2 are the same size? " + compareStructs(size1, size2)); // false
不知道你这个问题是否已经解决, 如果还没有解决的话: