java中怎么往集合类set里添加数据??

java中怎么往集合类set里添加数据??,第1张

java中往集合添加数据调用add();方法就行

//第一步先创建一个set集合的子类

HashSet has=new HashSet<>()

//给set集合添加的方法是add()

has.add(args)

资料拓展:

Collection接口可以存放重复元素,也可以存放不重复元素。List可以存放重复元素,Set就是不重复的元素。 

通过元素的equals方法,来判断是否为重复元素。 

Set集合取出元素的方式可以采用:迭代器,增强 for

CGLib(Code Generation Library)是一个强大的,高性能,高质量的字节码 *** 作类库,它可以在运行期扩展Java类与实现Java接口,Spring、Hibernate等很多著名的框架都使用了它。

使用cglib动态为Java类添加方法

public class CGLibExample {

@SuppressWarnings("unchecked")

public static void main(String[] args) {

// 定义一个参数是字符串类型的setCreatedAt方法

InterfaceMaker im = new InterfaceMaker()

im.add(new Signature("setCreatedAt", Type.VOID_TYPE,

new Type[] { Type.getType(String.class) }), null)

Class myInterface = im.create()

Enhancer enhancer = new Enhancer()

enhancer.setSuperclass(ExampleBean.class)

enhancer.setInterfaces(new Class[] { myInterface })

enhancer.setCallback(new MethodInterceptor() {

public Object intercept(Object obj, Method method, Object[] args,

MethodProxy proxy) throws Throwable {

ExampleBean bean = (ExampleBean) obj

// 调用字符串类型的setCreatedAt方法时,转换成Date型后调用Setter

if (method.getName().startsWith("setCreatedAt")

&&args[0] != null &&args[0] instanceof String) {

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd")

Date date = null

try {

date = sdf.parse((String) args[0])

} catch (final Exception e) { /* nop */ }

bean.setCreatedAt(date)

return null

}

return proxy.invokeSuper(obj, args)

}

})

// 生成一个Bean

ExampleBean bean = (ExampleBean) enhancer.create()

bean.setId(999)

try {

Method method = bean.getClass().getMethod("setCreatedAt", new Class[] {String.class})

method.invoke(bean, new Object[]{"20100531"})

} catch (final Exception e) {

e.printStackTrace()

}

System.out.printf("id : [%d] createdAt : [%s]\n", bean.getId(), bean.getCreatedAt())

}

}

class ExampleBean implements Serializable {

private static final long serialVersionUID = -8121418052209958014L

private int id

private Date createdAt

public int getId() {

return id

}

public void setId(int id) {

this.id = id

}

public Date getCreatedAt() {

return createdAt

}

public void setCreatedAt(Date createdAt) {

this.createdAt = createdAt

}

}

一般的程序库不允许直接修改,可利用继承来做。

举个例子,你要程序库中的类是Class A,你就写:

public Class B extends Class A {

public void methodA()

}

一般Class B只有你自己能用,除非再到网上分发出去。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/7913662.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-11
下一篇2023-04-11

发表评论

登录后才能评论

评论列表(0条)

    保存