Alibaba_equals与==的区别

本文详细解析了Java中字符串的equals方法与==符号的区别,包括它们的工作原理和应用场景,通过实例展示了如何正确使用这两个方法进行字符串比较。

1、==双等号

==比较的是两个对象在内存中的地址是否一致。比如

String s1 = "GoodNite";

String s2 = s1;

根据Java新建对象的原则,则s1 == s2返回true;而如果

String s1 = "GoodNite";

String s2 = new String("GoodNite");

那么s1 == s2则返回false。

2、equals方法

该方法定义于Object类中,源代码为:

public boolean equals(Object obj){

    return (this == obj);

}

我们不难发现,其实Object类中的原始equals函数也是调用了==符号。如果一个类(所有的类都继承自Object)并没有重写equals方法,那么使用equals方法与==是一样的结果。

3、String的例子

public boolean equals(Object anObject) {
 if (this == anObject) {
     return true;
 }
 if (anObject instanceof String) {
     String anotherString = (String)anObject;
     int n = count;
     if (n == anotherString.count) {
  char v1[] = value;
  char v2[] = anotherString.value;
  int i = offset;
  int j = anotherString.offset;
  while (n-- != 0) {
      if (v1[i++] != v2[j++])
   return false;
  }
  return true;
     }
 }
 return false;
    }
设计思路为:如果两个对象地址值一样,那么当然是相等的返回true;

而如果地址值不相等则开始判断它们的字符串数组是否相等。即String的equals方法先根据内存地址判断,再根据String内容判断。

所以,上面的例子:

String s1 = "GoodNite";

String s2 = new String("GoodNite");

s1.equals(s2)返回的是true。

重写equals方法的还有原始数据的封装类。

package com.api.ml.johnson.rscdbml.action; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.api.ml.base.action.AbstractWfAction; import com.api.ml.base.util.CusDaoUtil; import com.api.ml.base.util.CusDataUtil; import com.api.ml.base.util.CusHttpUtil; import com.api.ml.johnson.rscdbml.ActionLogBiz; import com.api.ml.johnson.rscdbml.config.ApiFieldMapConfig; import com.api.ml.johnson.rscdbml.config.ApiFieldMapItem; import com.api.ml.johnson.rscdbml.testdata.RscdbTestData; import weaver.conn.RecordSet; import weaver.conn.RecordSetTrans; import weaver.general.Util; import weaver.soa.workflow.request.RequestInfo; public class RscdbAction extends AbstractWfAction{ public String configFlag = ""; public String getConfigFlag() {return this.configFlag;} public void setConfigFlag(String configFlag) {this.configFlag = configFlag;} public String fromDetailIndex = ""; public String getFromDetailIndex() {return this.fromDetailIndex;} public void setFromDetailIndex(String fromDetailIndex) {this.fromDetailIndex = fromDetailIndex;} public String fieldNameHasmdrim = ""; public String getFieldNameHasmdrim() {return this.fieldNameHasmdrim;} public void setFieldNameHasmdrim(String fieldNameHasmdrim) {this.fieldNameHasmdrim = fieldNameHasmdrim;} public String fieldNameMarket = ""; public String getFieldNameMarket() {return this.fieldNameMarket;} public void setFieldNameMarket(String fieldNameMarket) {this.fieldNameMarket = fieldNameMarket;} public String marketValues = ""; public String getMarketValues() {return this.marketValues;} public void setMarketValues(String marketValues) {this.marketValues = marketValues;} public String marketValues_A91 = ""; public String getMarketValues_A91() {return this.marketValues_A91;} public void setMarketValues_A91(String marketValues_A91) {this.marketValues_A91 = marketValues_A91;} public String marketValues_action = ""; public String getMarketValues_action() {return this.marketValues_action;} public void setMarketValues_action(String marketValues_action) {this.marketValues_action = marketValues_action;} private static final String SPERATOR = "_,_,_"; public ActionResult doExceute(RequestInfo requestInfo, WfBaseInfo wfBaseInfo) throws Exception { RecordSet rsData = new RecordSet(); String mainFieldValue_market = CusDaoUtil.getFirstColumn(rsData, "select " + this.getFieldNameMarket() + " from " + wfBaseInfo.getMaintablename() + " where requestid=?", wfBaseInfo.getRequestid()); boolean isContainMarket_action = CusDataUtil.isStrInStr(mainFieldValue_market, this.getMarketValues_action()); if(!isContainMarket_action) { // this.writeMessage(requestInfo, "RSC DB API Call Action not found"); this.getCusLogUtil().writeCusLog("mainFieldValue_market:" + mainFieldValue_market); this.getCusLogUtil().writeCusLog("marketValues_action:" + this.marketValues_action); this.getCusLogUtil().writeCusLog("直接通过"); return ActionResult.Y; } ApiFieldMapConfig afmConfig = new ApiFieldMapConfig(this.getConfigFlag()); ActionLogBiz actionLogBiz = new ActionLogBiz(); if(afmConfig.isFound()) { CusHttpUtil cusHttpUtil = CusHttpUtil.getInstanceByUrl(afmConfig.getFullApiUrl()); ApiFieldMapItem afmItem_state = afmConfig.getResponseAfmItem("LOG_STATE"); ApiFieldMapItem afmItem_message = afmConfig.getResponseAfmItem("LOG_MESSAGE"); Map<String, Object> otherInfoMap = new HashMap<String, Object>(); List<JSONObject> bodyList = afmConfig.getRequestBodyList(ApiFieldMapConfig.TYPE_WF, wfBaseInfo.getMaintablename(), wfBaseInfo.getRequestid(), otherInfoMap); List<String> detailIdList = (List<String>) otherInfoMap.get("detailIdList"); this.getCusLogUtil().writeCusLog("detailIdList:" + detailIdList); JSONObject result = null; JSONArray rows = new JSONArray(); //key-来源明细的明细行ID, value-接口返回的数据行在汇总数据中的索引 Map<String, List<String>> detailIdRowIndexListMap = new HashMap<String, List<String>>(); //key-来源明细的明细ID, value-额外添加的row Map<String, JSONObject> detailIdExtraRowMap = new HashMap<String, JSONObject>(); int totalRowIndex = 0; ApiFieldMapItem afmItem_hasmdrim = afmConfig.getResponseAfmItem("A21"); int detailIndex = Util.getIntValue(this.getFromDetailIndex()); //关联字段 List<ApiFieldMapItem> afmItemList_key = afmConfig.getRequestAfmItemListByPrefix("JOINKEY_"); //源明细赋值字段 List<ApiFieldMapItem> afmItemList_sourceField = new ArrayList<ApiFieldMapItem>(); List<String> sourceFieldSqlNameList = new ArrayList<String>(); for(ApiFieldMapItem afmItem:afmConfig.getResponseFieldMap().values()) { String prefix = "FDT" + detailIndex + "_"; String operationFlag = afmItem.getOperationFlagByPrefix(prefix); if(!"".equals(operationFlag)) { afmItemList_sourceField.add(afmItem); sourceFieldSqlNameList.add(operationFlag.substring(prefix.length())); } } String mainid = CusDaoUtil.getFirstColumn(rsData, "select id from " + wfBaseInfo.getMaintablename() + " where requestid=?", wfBaseInfo.getRequestid()); for(int bodyNum=0;bodyNum<bodyList.size();bodyNum++) { String currentDetailId = detailIdList.get(bodyNum); JSONObject body = bodyList.get(bodyNum); this.getCusLogUtil().writeCusLog("index:" + (bodyNum + 1) + "/" + bodyList.size() + ", body:" + body); JSONObject result_part = null; if("TESTDATA_RSCDB".equals(afmConfig.getFullApiUrl())) { RscdbTestData rscdbTestData = new RscdbTestData(); Date date = new Date(); result_part = rscdbTestData.getResult(body); actionLogBiz.addLog("RSCDB", wfBaseInfo.getRequestid() + "", date, "建模模拟数据, 固定成功", "S", "建模模拟数据, 固定成功"); }else { Map<String, String> header = new HashMap<String, String>(); header.put("Authorization", "Bearer " + CusDataUtil.getConfigValue("RSDBCML_RSCDB_TOKEN")); Date date = new Date(); result_part = cusHttpUtil.sendPostForJson_TE(afmConfig.getFullApiUrl(), body, header); String value_state = afmItem_state==null?"":afmConfig.getRFValue(result_part, afmItem_state); String value_message = afmItem_message==null?"":afmConfig.getRFValue(result_part, afmItem_message); actionLogBiz.addLog("RSCDB", wfBaseInfo.getRequestid() + "", date, cusHttpUtil.getLastStatusLineString(), value_state, value_message); } if(result_part!=null) { this.getCusLogUtil().writeCusLog("index:" + (bodyNum + 1) + "/" + bodyList.size() + ", result old:"); this.getCusLogUtil().writeCusLog(result_part); //返回数据处理 ApiFieldMapItem afmItem_table = afmConfig.getResponseAfmItem("A31"); this.getCusLogUtil().writeCusLog("afmItem_table:" + afmItem_table.getApiFieldName()); JSONArray rows_part = (JSONArray) afmConfig.getResponseData(result_part, afmItem_table); this.getCusLogUtil().writeCusLog("rows:" + rows_part); List<String> rowIndexList = detailIdRowIndexListMap.get(currentDetailId); if(rowIndexList==null) { rowIndexList = new ArrayList<String>(); detailIdRowIndexListMap.put(currentDetailId, rowIndexList); } for(int i=0;i<rows_part.size();i++) { rowIndexList.add("" + totalRowIndex++); } //对每批返回数据的rows事先做处理, 然后再合并 Set<String> detailIdSet = new HashSet<String>(); String sqlDetail = "select * from " + wfBaseInfo.getDetailtablename(detailIndex) + " where mainid=? and id=?"; rsData.executeQuery(sqlDetail, mainid, currentDetailId); while(rsData.next()) { String detailId = Util.null2String(rsData.getString("id")); for(int i=0;i<rows_part.size();i++) { JSONObject row = rows_part.getJSONObject(i); boolean flag = true; for(int k=0;k<afmItemList_key.size();k++) { String operateFlag = afmItemList_key.get(k).getOperationFlagByPrefix("JOINKEY_"); ApiFieldMapItem responseAfmItem = afmConfig.getResponseAfmItem(operateFlag); String rowValue = Util.null2String(row.getString(responseAfmItem.getApiFieldName())); String detailValue = Util.null2String(rsData.getString(afmItemList_key.get(k).getLocalFieldName())); if(!rowValue.equals(detailValue)) { flag = false; break; } } if(flag) { detailIdSet.add(detailId); for(int k=0;k<afmItemList_sourceField.size();k++) { row.put(afmItemList_sourceField.get(k).getApiFieldName(), Util.null2String(rsData.getString(sourceFieldSqlNameList.get(k)))); } row.put(afmItem_hasmdrim.getApiFieldName(), "Y"); } } } //A21 rsData.beforFirst(); List<String> detailIdList_Y = new ArrayList<String>(); List<String> detailIdList_N = new ArrayList<String>(); while(rsData.next()) { String detailId = Util.null2String(rsData.getString("id")); if(detailIdSet.contains(detailId)) {//Y detailIdList_Y.add(detailId); }else {//N detailIdList_N.add(detailId); } } RecordSetTrans rst = new RecordSetTrans(); rst.setAutoCommit(false); try { if(detailIdList_Y.size()>0) { String updateSql_Y = "update " + wfBaseInfo.getDetailtablename(detailIndex) + " set " + this.getFieldNameHasmdrim() + "=? where id in (" + String.join(",", detailIdList_Y) +")"; rst.executeUpdate(updateSql_Y, "Y"); } if(detailIdList_N.size()>0) { String updateSql_N = "update " + wfBaseInfo.getDetailtablename(detailIndex) + " set " + this.getFieldNameHasmdrim() + "=? where id in (" + String.join(",", detailIdList_N) +")"; rst.executeUpdate(updateSql_N, "N"); } rst.commit(); }catch(Exception e) { rst.rollback(); } //A21-END rsData.beforFirst(); while(rsData.next()) { String detailId = Util.null2String(rsData.getString("id")); if(!detailIdSet.contains(detailId)) { JSONObject newRow = new JSONObject(); for(int k=0;k<afmItemList_key.size();k++) { newRow.put(afmItemList_key.get(k).getApiFieldName(), Util.null2String(rsData.getString(afmItemList_key.get(k).getLocalFieldName()))); } for(int k=0;k<afmItemList_sourceField.size();k++) { newRow.put(afmItemList_sourceField.get(k).getApiFieldName(), Util.null2String(rsData.getString(sourceFieldSqlNameList.get(k)))); } newRow.put(afmItem_hasmdrim.getApiFieldName(), "N"); rows_part.add(newRow); detailIdExtraRowMap.put(currentDetailId, newRow); totalRowIndex++; } } this.getCusLogUtil().writeCusLog("rows after operation:" + rows_part); if(result==null) { result = result_part; rows = rows_part; }else { rows.addAll(rows_part); } }else { this.getCusLogUtil().writeCusLog("未获取到接口返回数据"); } } if(result!=null) { //存储所有需要被移除的行索引, 最后一起移除 List<Integer> toRemovedRowIndexList = new ArrayList<Integer>(); //判断接口数据明细中是否包含指定的market字段 boolean isContainMarket = CusDataUtil.isStrInStr(mainFieldValue_market, this.getMarketValues()); if(!isContainMarket) { //步骤-A4 this.getCusLogUtil().writeCusLog("A4"); this.getCusLogUtil().writeCusLog("A4 rows:" + rows); ApiFieldMapItem afmItem_licensestatus = afmConfig.getResponseAfmItem("A41"); for(int i=rows.size()-1;i>=0;i--) { if(toRemovedRowIndexList.contains(i)) continue; if(!"Y".equals(Util.null2String(rows.getJSONObject(i).getString(afmItem_hasmdrim.getApiFieldName())))) continue; if(Util.null2String(rows.getJSONObject(i).getString(afmItem_licensestatus.getApiFieldName())).toUpperCase().indexOf("INACTIVE")>-1) { //rows.remove(i); toRemovedRowIndexList.add(i); } } } //步骤-A51 boolean isContainMarket_A91 = CusDataUtil.isStrInStr(mainFieldValue_market, this.getMarketValues_A91()); if(isContainMarket_A91) { this.getCusLogUtil().writeCusLog("A91"); this.getCusLogUtil().writeCusLog("A91 rows:" + rows); ApiFieldMapItem afmItem_locallicenseholder = afmConfig.getResponseAfmItem("A91"); for(int i=rows.size()-1;i>=0;i--) { if(toRemovedRowIndexList.contains(i)) continue; if(!"Y".equals(Util.null2String(rows.getJSONObject(i).getString(afmItem_hasmdrim.getApiFieldName())))) continue; String value_A91 = Util.null2String(rows.getJSONObject(i).getString(afmItem_locallicenseholder.getApiFieldName())); if(!"".equals(value_A91)) { //rows.remove(i); toRemovedRowIndexList.add(i); } } } //步骤-A5 this.getCusLogUtil().writeCusLog("A5"); this.getCusLogUtil().writeCusLog("A5 rows:" + rows); ApiFieldMapItem afmItem_importmanufacturerslabelasis = afmConfig.getResponseAfmItem("A51"); ApiFieldMapItem afmItem_addrelabelingrepackaging = afmConfig.getResponseAfmItem("A52"); for(int i=rows.size()-1;i>=0;i--) { if(toRemovedRowIndexList.contains(i)) continue; if(!"Y".equals(Util.null2String(rows.getJSONObject(i).getString(afmItem_hasmdrim.getApiFieldName())))) continue; String value_A51 = Util.null2String(rows.getJSONObject(i).getString(afmItem_importmanufacturerslabelasis.getApiFieldName())); String value_A52 = Util.null2String(rows.getJSONObject(i).getString(afmItem_addrelabelingrepackaging.getApiFieldName())); if((("No".equals(value_A51)||"".equals(value_A51))&&("No".equals(value_A52)||"".equals(value_A52))) ||("No".equals(value_A51)&&"No - Regulatory Eligibility Not Confirmed".equals(value_A52))) { //rows.remove(i); toRemovedRowIndexList.add(i); } } //开始移除row Collections.sort(toRemovedRowIndexList); Collections.reverse(toRemovedRowIndexList); this.getCusLogUtil().writeCusLog("toRemovedRowIndexList:" + toRemovedRowIndexList); this.getCusLogUtil().writeCusLog("detailIdRowIndexListMap 1:" + detailIdRowIndexListMap); for(int i=0;i<toRemovedRowIndexList.size();i++) { int rowIndex = toRemovedRowIndexList.get(i).intValue(); rows.remove(rowIndex); for(Map.Entry<String, List<String>> entry:detailIdRowIndexListMap.entrySet()) { List<String> rowIndexList = entry.getValue(); rowIndexList.remove(rowIndex + ""); } } this.getCusLogUtil().writeCusLog("detailIdRowIndexListMap 2:" + detailIdRowIndexListMap); List<String> fromDtDeatilIdList = new ArrayList<String>(); for(Map.Entry<String, List<String>> entry:detailIdRowIndexListMap.entrySet()) { String fromDtDeatilId = entry.getKey(); List<String> rowIndexList = entry.getValue(); if(rowIndexList.size()==0) { fromDtDeatilIdList.add(fromDtDeatilId); JSONObject row = detailIdExtraRowMap.get(fromDtDeatilId); if(row!=null) { row.put(afmItem_hasmdrim.getApiFieldName(), "N"); } } } this.getCusLogUtil().writeCusLog("fromDtDeatilIdList:" + fromDtDeatilIdList); if(fromDtDeatilIdList.size()>0) { RecordSetTrans rst = new RecordSetTrans(); rst.setAutoCommit(false); try { String updateSql = "update " + wfBaseInfo.getDetailtablename(detailIndex) + " set " + this.getFieldNameHasmdrim() + "=? where id in (" + String.join(",", fromDtDeatilIdList) +")"; this.getCusLogUtil().writeCusLog("updateSql:" + updateSql); rst.executeUpdate(updateSql, "N"); rst.commit(); }catch(Exception e) { rst.rollback(); } } // //步骤-A6 // this.getCusLogUtil().writeCusLog("A6"); // this.getCusLogUtil().writeCusLog("A6 rows:" + rows); // ApiFieldMapItem afmItem_catalognumber = afmConfig.getResponseAfmItem("A61"); ApiFieldMapItem afmItem_mdrimmaterialnumber = afmConfig.getResponseAfmItem("A62");// ApiFieldMapItem afmItem_franchisepm = afmConfig.getResponseAfmItem("A63"); // List<Integer> toRemoveIdList = new ArrayList<Integer>(); // Map<String, Integer> keyMap = new HashMap<String, Integer>(); // for(int i=rows.size()-1;i>=0;i--) { // if(!"Y".equals(Util.null2String(rows.getJSONObject(i).getString(afmItem_hasmdrim.getApiFieldName())))) continue; // String key = Util.null2String(rows.getJSONObject(i).getString(afmItem_catalognumber.getApiFieldName())) + SPERATOR // + Util.null2String(rows.getJSONObject(i).getString(afmItem_mdrimmaterialnumber.getApiFieldName())); // if(keyMap.containsKey(key)) { // toRemoveIdList.add(i); // int sIndex = keyMap.get(key); // JSONObject json = rows.getJSONObject(sIndex); // json.put(afmItem_franchisepm.getApiFieldName(), Util.null2String(json.getString(afmItem_franchisepm.getApiFieldName())) // + "|" + Util.null2String(rows.getJSONObject(i).getString(afmItem_franchisepm.getApiFieldName()))); // }else { // keyMap.put(key, i); // } // } // this.getCusLogUtil().writeCusLog("A6 toRemoveIdList:" + toRemoveIdList); // for(int i=0;i<toRemoveIdList.size();i++) { // rows.remove(toRemoveIdList.get(i).intValue()); // } //步骤-A7 //afmItem_mdrimmaterialnumber this.getCusLogUtil().writeCusLog("A7"); this.getCusLogUtil().writeCusLog("A7 rows:" + rows); // ApiFieldMapItem afmItem_market = afmConfig.getResponseAfmItem("A71"); ApiFieldMapItem afmItem_division = afmConfig.getResponseAfmItem("A72"); ApiFieldMapItem afmItem_modcode = afmConfig.getResponseAfmItem("A73"); ApiFieldMapItem afmItem_franchiselm = afmConfig.getResponseAfmItem("A74"); Pattern pattern = Pattern.compile("(^-[0-9]{2}$)"); String modeTableName_A7 = CusDataUtil.getConfigValue("RSDBCML_A7_MODETABLENAME"); // String modeFieldName_market = CusDataUtil.getConfigValue("RSDBCML_A7_MODEFIELD_MARKET"); String modeFieldName_division = CusDataUtil.getConfigValue("RSDBCML_A7_MODEFIELD_DIVISION"); String modeFieldName_modcode = CusDataUtil.getConfigValue("RSDBCML_A7_MODEFIELD_MODCODE"); String modeFieldName_franchiselm = CusDataUtil.getConfigValue("RSDBCML_A7_MODEFIELD_FRANCHISELM"); String modeFieldName_franchisepm = CusDataUtil.getConfigValue("RSDBCML_A7_MODEFIELD_FRANCHISEPM"); for(int i=0;i<rows.size();i++) { if(!"Y".equals(Util.null2String(rows.getJSONObject(i).getString(afmItem_hasmdrim.getApiFieldName())))) continue; String fieldValue1 = Util.null2String(rows.getJSONObject(i).getString(afmItem_mdrimmaterialnumber.getApiFieldName())); //最后三位是否为横杠加数字 boolean flag = false; String finalStr = ""; if(fieldValue1.length()>3) { String endStr = fieldValue1.substring(fieldValue1.length()-3); Matcher matcher = pattern.matcher(endStr); if(matcher.find()) { flag = true; finalStr = endStr.substring(1); } } if(!flag) { // String rowFieldValue_market = Util.null2String(rows.getJSONObject(i).getString(afmItem_market.getApiFieldName())); String rowFieldValue_division = Util.null2String(rows.getJSONObject(i).getString(afmItem_division.getApiFieldName())); String rowFieldValue_franchiselm = Util.null2String(rows.getJSONObject(i).getString(afmItem_franchiselm.getApiFieldName())); String rowFieldValue_franchisepm = Util.null2String(rows.getJSONObject(i).getString(afmItem_franchisepm.getApiFieldName())); if("MP".equals(rowFieldValue_division)) { String sql = "select " + modeFieldName_modcode + " from " + modeTableName_A7 + " where " + modeFieldName_franchiselm + "=? and " + modeFieldName_franchisepm + "=?"; String modeFieldValue_modcode = CusDaoUtil.getFirstColumn(rsData, sql, rowFieldValue_franchiselm, rowFieldValue_franchisepm); finalStr = modeFieldValue_modcode; }else { String sql = "select " + modeFieldName_modcode + " from " + modeTableName_A7 + " where " + modeFieldName_division + "=?"; String modeFieldValue_modcode = CusDaoUtil.getFirstColumn(rsData, sql, rowFieldValue_division); finalStr = modeFieldValue_modcode; } } rows.getJSONObject(i).put(afmItem_modcode.getApiFieldName(), finalStr); } this.getCusLogUtil().writeCusLog("result new"); this.getCusLogUtil().writeCusLog(result); //操作数据 if(afmConfig.operateResponseBody(result, ApiFieldMapConfig.TYPE_WF, wfBaseInfo.getMaintablename(), wfBaseInfo.getRequestid())) { this.getCusLogUtil().writeCusLog("返回报文更新成功"); }else { this.writeMessage(requestInfo, "返回报文更新失败"); return ActionResult.N; } } }else { this.writeMessage(requestInfo, "未找到配置"); return ActionResult.N; } return ActionResult.Y; } } 解释一下这个代码,什么时候会移除数据
10-11
帮我加个注释 package com.jd.tag; // created by wudong91 on 2025/1/23 10:29 import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.jd.util.AppVersionCompare; import com.jd.util.RegexpUtils; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; public class OfflineProcessTagUDTF extends GenericUDTF { private static final Logger log = LoggerFactory.getLogger(OfflineProcessTagUDTF.class); private static final String pathDimTrafficMap = "hdfs://ns1001/user/mart_sch/app.db/app_jdr_trafficmap_location_parse_path_a_d_d"; private static final String pathDimTagSupplement = "hdfs://ns1/user/dd_edw/dim.db/dim_jdr_sch_tag_supplement_white_event_id"; private static final Set<String> whiteEventIdSet = TagEvent.getTagEvent(pathDimTrafficMap); private static final Set<String> cartWhiteEventIdSet = TagEvent.getTagEvent(pathDimTagSupplement, function -> "大盘加购".equals(function.apply("comment"))); private static final Set<String> supplementWhiteEventIdSet = TagEvent.getTagEvent(pathDimTagSupplement, function -> "归因".equals(function.apply("comment"))); private static final Set<String> clearAllPageIdSet = new HashSet<>(Arrays.asList("Home_Main", "MyJD_Main")); private static final Set<String> debouncePageIdSet = new HashSet<>(Arrays.asList("Live_VerticalVideo")); public static final String PAGE_VIEW = "pageview"; public static final String CLICK = "click"; public static final String TYPE = "type"; public static final String PID = "pid"; public static final String JD_LOG_ID = "jd_log_id"; public static final String CTM = "ctm"; public static final String EID = "eid"; public static final String PV = "pv"; public static final String CL = "cl"; public static final String SPM = "spm"; public static final String CLEAR_TAG = "clear_tag"; public static final String SEP = "_"; private final RegexpUtils regexpUtils = new RegexpUtils(); private final List<String> jdTagPageIdList = new ArrayList<>(); private final JSONArray jdTag = new JSONArray(); private final JSONObject currentPvTag = new JSONObject(); private String lastSessionId; private String lastPageId; private boolean lastPageIsRollBack = false; private boolean lastClickIsClickClear = false; // debug字段 private boolean clickClearFlag = false; private boolean debouncePageFlag = false; private boolean maxDepthFlag = false; @Override public StructObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException { ArrayList<String> fieldNameList = new ArrayList<>(); fieldNameList.add("jd_tag"); fieldNameList.add("debug_info"); List<ObjectInspector> fieldOIs = new ArrayList<>(); fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector); fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector); return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNameList, fieldOIs); } @Override public void process(Object[] objects) throws HiveException { int maxDepth = Integer.parseInt(Optional.ofNullable(objects[0]).orElse("0").toString()); String eventType = Optional.ofNullable(objects[1]).orElse("").toString(); String maLogId = Optional.ofNullable(objects[2]).orElse("").toString(); String sessionId = Optional.ofNullable(objects[3]).orElse("").toString(); String pageId = Optional.ofNullable(objects[4]).orElse("").toString(); String eventId = Optional.ofNullable(objects[5]).orElse("").toString(); String deviceTs = Optional.ofNullable(objects[6]).orElse("").toString(); String spm = Optional.ofNullable(objects[7]).orElse("").toString(); String rollBack = Optional.ofNullable(objects[8]).orElse("").toString(); String appVersion = Optional.ofNullable(objects[9]).orElse("").toString(); boolean isPv = PAGE_VIEW.equals(eventType); // 浏览截断 boolean isPvClear = isPv && clearAllPageIdSet.contains(pageId); // 点击截断 boolean isClickClear = CLICK.equals(eventType) && ( ("NavigationBar_Main".equals(pageId) && !"NavigationBar_ButtonMarket".equals(eventId)) || "Home_TopTab".equals(eventId) ); /* * 【截断】session截断 * */ if (!sessionId.equals(lastSessionId)) { clearTag(true); lastSessionId = sessionId; } /* * 【截断】浏览、点击截断 * */ if (isPvClear || isClickClear) { clearTag(isPvClear); if (isClickClear) { lastClickIsClickClear = true; clickClearFlag = true; } else { clickClearFlag = false; } } lastPageId = (isPv || lastPageId == null) ? pageId : lastPageId; if (isPv) { currentPvTag.clear(); } if (isPv || whiteEventIdSet.contains(eventId) || supplementWhiteEventIdSet.contains(eventId) || cartWhiteEventIdSet.contains(eventId.toLowerCase()) || regexpUtils.like(eventId.toLowerCase(), "babel.*") || StringUtils.isNotBlank(spm) ) { if (isPv) { if (AppVersionCompare.evaluate(appVersion) >= AppVersionCompare.evaluate("15.1.35")) { lastPageIsRollBack = "1".equals(rollBack); if (lastPageIsRollBack) { delTagItemRollBack(lastPageId); } } else { delTagItemRollBack(lastPageId); } } else if (!jdTag.isEmpty()) { jdTag.remove(jdTag.size() - 1); } // 控制最大深度 if (jdTag.size() >= maxDepth) { jdTagPageIdList.remove(0); jdTag.remove(0); maxDepthFlag = true; } // 连续触发的页面场景特殊处理 if (isPv && debouncePageIdSet.contains(lastPageId) && !jdTagPageIdList.isEmpty() && jdTagPageIdList.get(jdTagPageIdList.size() - 1).equals(lastPageId) ) { debouncePageFlag = true; try { jdTag.remove(jdTag.size() - 1); jdTagPageIdList.remove(jdTagPageIdList.size() - 1); } catch (Exception e) { log.error("[Error] No tag found for page id: {}, jdTag: {}, jdTagPageIdList: {}, isPvClear: {}, lastPageIsRollBack: {}, session_id: {}, ma_log_id: {}", lastPageId, jdTag, jdTagPageIdList, isPvClear, lastPageIsRollBack, sessionId, maLogId); throw new HiveException(e); } } else if (isPv) { debouncePageFlag = false; } // 更新当前浏览tag信息 if (isPv) { currentPvTag .fluentPut(PV + SEP + CTM, deviceTs) .fluentPut(PV + SEP + JD_LOG_ID, maLogId) .fluentPut(PV + SEP + SPM, spm); lastClickIsClickClear = false; } if (isPv || currentPvTag.getString(PID) == null) { currentPvTag.put(PID, lastPageId); jdTagPageIdList.add(lastPageId); } JSONObject tag = new JSONObject(); tag.putAll(currentPvTag); // 更新当前点击tag信息 if (CLICK.equals(eventType)) { tag .fluentPut(CL + SEP + CTM, deviceTs) .fluentPut(CL + SEP + JD_LOG_ID, maLogId) .fluentPut("cur_" + CL + SEP + SPM, spm) .fluentPut(EID, eventId); if (lastClickIsClickClear) { tag.fluentPut(CLEAR_TAG, "1"); } } jdTag.add(tag); } forward(new Object[]{jdTag.toJSONString(), generateDebugInfo()}); } public String generateDebugInfo() { JSONObject debug_info = new JSONObject(); debug_info.put("max_depth_flag", String.valueOf(maxDepthFlag)); debug_info.put("click_clear_flag", String.valueOf(clickClearFlag)); debug_info.put("debounce_page_flag", String.valueOf(debouncePageFlag)); return debug_info.toJSONString(); } public void delTagItemRollBack(String pageId) { if (!jdTagPageIdList.contains(pageId)) { return; } for (int i = jdTag.size() - 1; i >= 0; i--) { JSONObject jsonObject = jdTag.getJSONObject(i); String item_pid = jsonObject.getString(PID); jdTag.remove(i); jdTagPageIdList.remove(i); if (item_pid.equals(pageId)) { return; } } } public void clearTag(boolean isPvClear) { jdTag.clear(); if (isPvClear) { lastPageId = null; } currentPvTag.clear(); jdTagPageIdList.clear(); lastPageIsRollBack = false; lastClickIsClickClear = false; clickClearFlag = false; debouncePageFlag = false; maxDepthFlag = false; } @Override public void close() throws HiveException { } }
09-06
List<WebInvCockpitReqVo.StratConfigStock> stratList = reqVO.getStockList(); if(!stratList.isEmpty()) { for (WebInvCockpitReqVo.StratConfigStock vo : stratList) { String stockCode = vo.getStockCode(); BigDecimal origPos; if (!positions.isEmpty()) { for (String position : positions.keySet()) { //遍历该用户的持仓数据 if (StringUtils.equals(position, stockCode)) { com.alibaba.fastjson.JSONObject stock = positions.getJSONObject(position); BigDecimal amount = stock.getBigDecimal("amount"); BigDecimal last_price = stock.getBigDecimal("last_price"); //排除amount为0的情况 if (amount.compareTo(BigDecimal.ZERO) == 0) { continue; } origPos = amount.multiply(last_price); totalOrigPos = totalOrigPos.add(origPos); haveOrigPso = true; } } allOrigPos = allOrigPos.add(totalOrigPos); //1.有该只股票的持仓 if (haveOrigPso) { BigDecimal multiply = totalPosSizeAmount.multiply(BigDecimal.valueOf(0.15)); //当前该只股票能买到的最大额度 BigDecimal oneCost = toadyLeftAmount.multiply(vo.getHoldingRatio()); if (totalOrigPos.add(oneCost).compareTo(multiply) > 0) { toadyLeftAmount = totalAssert.multiply(BigDecimal.valueOf(0.15)).subtract(totalOrigPos).divide(vo.getHoldingRatio()); } //2.没有该只股票的持仓 } else { BigDecimal multiply = totalPosSizeAmount.multiply(BigDecimal.valueOf(0.05)); BigDecimal oneCost = toadyLeftAmount.multiply(vo.getHoldingRatio()); if (oneCost.compareTo(multiply) > 0) { //调整可用金额 toadyLeftAmount = totalAssert.multiply(BigDecimal.valueOf(0.05)).divide(vo.getHoldingRatio()); } } } } }else { for (WebInvCockpitReqVo.StratConfigStock vo : stratList) { String stockCode = vo.getStockCode(); BigDecimal origPos; if (!positions.isEmpty()) { for (String position : positions.keySet()) { //遍历该用户的持仓数据 if (StringUtils.equals(position, stockCode)) { com.alibaba.fastjson.JSONObject stock = positions.getJSONObject(position); BigDecimal amount = stock.getBigDecimal("amount"); BigDecimal last_price = stock.getBigDecimal("last_price"); //排除amount为0的情况 if (amount.compareTo(BigDecimal.ZERO) == 0) { continue; } origPos = amount.multiply(last_price); totalOrigPos = totalOrigPos.add(origPos); haveOrigPso = true; } } allOrigPos = allOrigPos.add(totalOrigPos); //1.有该只股票的持仓 if (haveOrigPso) { BigDecimal multiply = totalPosSizeAmount.multiply(BigDecimal.valueOf(0.15)); //当前该只股票能买到的最大额度 BigDecimal oneCost = toadyLeftAmount.multiply(vo.getHoldingRatio()); if (totalOrigPos.add(oneCost).compareTo(multiply) > 0) { toadyLeftAmount = totalAssert.multiply(BigDecimal.valueOf(0.15)).subtract(totalOrigPos).divide(vo.getHoldingRatio()); } //2.没有该只股票的持仓 } else { BigDecimal multiply = totalPosSizeAmount.multiply(BigDecimal.valueOf(0.05)); BigDecimal oneCost = toadyLeftAmount.multiply(vo.getHoldingRatio()); if (oneCost.compareTo(multiply) > 0) { //调整可用金额 toadyLeftAmount = totalAssert.multiply(BigDecimal.valueOf(0.05)).divide(vo.getHoldingRatio()); } } } } } 将我的代码简洁一下
10-24
提供了基于BP(Back Propagation)神经网络结合PID(比例-积分-微分)控制策略的Simulink仿真模型。该模型旨在实现对杨艺所著论文《基于S函数的BP神经网络PID控制器及Simulink仿真》中的理论进行实践验证。在Matlab 2016b环境下开发,经过测试,确保能够正常运行,适合学习和研究神经网络在控制系统中的应用。 特点 集成BP神经网络:模型中集成了BP神经网络用于提升PID控制器的性能,使之能更好地适应复杂控制环境。 PID控制优化:利用神经网络的自学习能力,对传统的PID控制算法进行了智能调整,提高控制精度和稳定性。 S函数应用:展示了如何在Simulink中通过S函数嵌入MATLAB代码,实现BP神经网络的定制化逻辑。 兼容性说明:虽然开发于Matlab 2016b,但理论上兼容后续版本,可能会需要调整少量配置以适配不同版本的Matlab。 使用指南 环境要求:确保你的电脑上安装有Matlab 2016b或更高版本。 模型加载: 下载本仓库到本地。 在Matlab中打开.slx文件。 运行仿真: 调整模型参数前,请先熟悉各模块功能和输入输出设置。 运行整个模型,观察控制效果。 参数调整: 用户可以自由调节神经网络的层数、节点数以及PID控制器的参数,探索不同的控制性能。 学习和修改: 通过阅读模型中的注释和查阅相关文献,加深对BP神经网络PID控制结合的理解。 如需修改S函数内的MATLAB代码,建议有一定的MATLAB编程基础。
使用java获取org=河源这个值,以下是json串{cool_6=直身框精光边,光刀,12, cool_7=粗孔,880喷钻,50, cool_8=粗孔,合金钻,50, cool_9=粗孔,皇冠钻,50, verticalHole=Y, lkmAddr=E-JG-1066.txt, discount=1, dn=cn=E-JG-1066,ou=13\#标准板线,ou=13\#厂,ou=机床,ou=河源, lkmOperatorList=[E0564116], lkmMachineNo=E-JG-1066, lkmProcessCategory=四侧组合, platforms=1,3,5,7, reportType=卧加精孔, cool_10=粗连中粗,倒圆立铣刀,12, lkmStartActiveTime=20241030141035Z, cool_12=精孔,可调试铰刀,50, cool_11=粗连中粗,日立铣刀,12, cool_14=钻倒角,1.2_16披锋刀,12, machineNo=E-JG-1066, holeBunchType=ROUGHDRILL, lkmMatchToolHeight=70.0, cool_13=精孔,合金铰刀,50, cool_16=钻托位,双锋拨头刀,8, cool_15=钻倒角,8_24披锋刀,12, cool_18=钻托位,拨头刀M12,8, cool_17=钻托位,拨头刀M10,8, group=13#标准板线, cool_19=钻托位,拨头刀M14,8, ip=E-JG-1066, objectClass=[lkmMachine], cool_21=钻托位,拨头刀M6,8, cool_20=钻托位,拨头刀M16,8, cool_23=锣倒角,1.2_16披锋刀,12, cool_22=钻托位,拨头刀M8,8, cool_25=锣倒角,8_24披锋刀,12, cool_24=锣倒角,10.5_17.1上下孔口倒角刀,12, lastUpdateTime=20251018 13:54:25, OverCardCheck=Y, lkmOperatorJson={"E0564116":"李德成"}, toolLibrary=锣孔工艺刀库(E-JG-1066), description=《自动化虚拟机床》未配电脑, Monitor=132.147.168.118, lkmAttrGroupId=E-JG-1066-1, lkmScannerIp=E-JG-1066, lkmIsEnable=TRUE, factory=13#厂, org=河源, coordinateSet=Y, isNeedReverseChamfer=Y, cn=E-JG-1066, ipHostNumber=E-JG-1066, lkmMachinecn=E-JG-1066, macVendor=OKUMA, discountNight=1, cool_1=中粗孔,粗波刀,8, cool_2=光底,倒圆立铣刀,12, cool_3=光底,日立铣刀,12, cool_4=公制牙,挤压丝锥,8, cool_5=直身框做精,倒圆立铣刀,12}
10-19
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值