Java的swap操作实现
swap的作用不必多说,c/c++中基于指针和引用,这两个功能有多强大更不用说。
Java底层隐藏了指针和引用,但是这并不妨碍我们的使用,毕竟java是面向对象语言。
方法1:
通过new对象,让堆存储变量
public static void swap(Member a, Member b){Integer temp = a.getI();a.setI(b.getI());b.setI(temp);}public static void main(String args[]) {Member a = new Member();a.setI(1);Member b = new Member();b.setI(2);swap(a, b);int o=0;}
Member是我自定义的对象
public class Member extends DateUtil{Integer i;String s;Boolean b;Long l;Double d;Float f;Character c;public Member(Integer i, String s, Boolean b, Long l, Double d, Float f, Character c) {this.i = i;this.s = s;this.b = b;this.l = l;this.d = d;this.f = f;this.c = c;}public Member() {
// this.i = 1;
// this.s = "s";
// this.b = true;
// this.l = 1L;
// this.d = 5.5;
// this.f = 6.5f;
// this.c = 'c';}public Integer getI() {return i;}public void setI(Integer i) {this.i = i;}public String getS() {return s;}public void setS(String s) {this.s = s;}public Boolean getB() {return b;}public void setB(Boolean b) {this.b = b;}public Long getL() {return l;}public void setL(Long l) {this.l = l;}public Double getD() {return d;}public void setD(Double d) {this.d = d;}public Float getF() {return f;}public void setF(Float f) {this.f = f;}public Character getC() {return c;}public void setC(Character c) {this.c = c;}@Overridepublic boolean equals(Object obj) {Member boardVo=(Member) obj;return i.equals(Member.this.i) && s.equals(Member.this.s);}@Overridepublic int hashCode() {String str=String.valueOf(i)+String.valueOf(s);return str.hashCode();}@Overridepublic String toString() {return "Member{" +"i=" + i +", s='" + s + '\'' +", b=" + b +", l=" + l +", d=" + d +", f=" + f +", c=" + c +'}';}
}
方法2:
引用
private static void swap(Integer a, Integer b) {if (a == null || b == null) {return;}//获得a的class对象Class integerClass = (Class) a.getClass();try {//获得value属性Field value=integerClass.getDeclaredField("value");//设置权限为可访问value.setAccessible(true);//交换int temp=a;value.setInt(a,b);value.setInt(b,temp);} catch (NoSuchFieldException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}
我个人在写算法的时候非常不喜欢这些拐弯抹角的写法,但是当这个逻辑扩展到业务的时候,swap这类的逻辑我们很少很少会用到,毕竟都是对对象操作,算法什么的Java的类库也有,复杂的代码逻辑后期会难以维护。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!