启天JAVA培训社区's Archiver

junsan 发表于 2008-10-28 13:59

jsf转换器中用到的hashCode和equals

作者:yourenyouyu2008

转换器一般是要将页面提交的字符串转换成对象(object)

public Object getAsObject(FacesContext context, UIComponent component,
   String value) {

  int index = value.indexOf(':');
  
  return new ToolBarItem(value.substring(0, index), value.substring(index + 1));
}

而页面显示的对象却是另一个对象,虽然他们的数据是相同的,但hascode却不同,这样转换后的对象是没法更新以前的对象的,特别是list中的,会报无效的表达式错误。但我们给ToolBarItem对象实现hashCode,equals方法后,相同的内容通过转换器转换出来的就是同一对象了,这样就可以更新了。

public ToolBar() {
  ToolBarItem item = new ToolBarItem();
  item.setIcon("create_folder");
  item.setLabel("Create Folder");
  items.add(item);
  item = new ToolBarItem();
  item.setIcon("create_doc");
  item.setLabel("Create Doc");
  items.add(item);
  item = new ToolBarItem();
  item.setIcon("find");
  item.setLabel("Find");
  items.add(item);





public class ToolBarItem {
private String icon;
private String label;
private String iconURI;

public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((icon == null) ? 0 : icon.hashCode());
result = prime * result + ((label == null) ? 0 : label.hashCode());
return result;
}



public boolean equals(Object obj) {
if (this == obj)
  return true;
if (obj == null)
  return false;
if (getClass() != obj.getClass())
  return false;
final ToolBarItem other = (ToolBarItem) obj;
if (icon == null) {
  if (other.icon != null)
   return false;
} else if (!icon.equals(other.icon))
  return false;
if (label == null) {
  if (other.label != null)
   return false;
} else if (!label.equals(other.label))
  return false;
return true;
}

页: [1]

Powered by Discuz! Archiver 6.1.0F  © 2001-2007 Comsenz Inc.